menu

Questions & Answers

use of :hover as a simplepseudos in csstype for typescript/react

I am using csstype in a react component library. I want to add a hover effect, which is supported through simple pseudos. Unfortunately I cannot find any example of this being used and I can't get it to work.

I have included some code below that expressed the idea of what I want to do, but I have no idea really

import CSS from "csstype";

export const DropdownContainer: CSS.Properties = {
  display: "grid",
  gridTemplateColumns: "3fr 15fr 30fr",
};

export const DropdownText: CSS.Properties = {
  placeSelf: 'start',
}

export const DropdownTextHov: { [P in CSS.SimplePseudos]?: CSS.Properties }  = {
  ':hover': {
    color: 'blue',
  },
}

<snipped code>

    return (
      <div style={DropdownContainer}>
        <p style={DropdownText}></p>
        <p style={{DropdownText} + {DropdownTextHov}}>this is text</p>
      </div>
    );

I have tried a number of alternatives. I have added the hover to DropdownText, but that doesn't work.

Comments:
2023-01-23 23:25:08
Alternatively, you can use a CSS module in your project and improve your CSS to SCSS. For example; import styles from './styles.css' and usage; <div className={styles.example}></div>
Answers(1) :

You can use the :hover pseudo-selector in the csstype library by including it in an object with the CSS.SimplePseudos type and adding the desired CSS properties. However, in your code, you are trying to apply the hover style to the p element by concatenating the DropdownText object and the DropdownTextHov object inside the style prop, which won't work. Instead, you need to use the spread operator (...) to apply both styles to the p element:

return (
  <div style={DropdownContainer}>
    <p style={DropdownText}></p>
    <p style={{...DropdownText, ...DropdownTextHov}}>this is text</p>
  </div>
);

This way you are spreading the properties of DropdownText and DropdownTextHov objects inside the style property. Now it will apply styles to the p element on hover.