Home > Mobile >  CSS attribute selectors in JSX with TypeScript
CSS attribute selectors in JSX with TypeScript

Time:02-02

I can do the following in pure HTML/CSS

<div color="red">
  red
</div>

<div color="yellow">
  yellow
</div>
div[color="red"] {
  color: red;
}

div[color="yellow"] {
  color: yellow;
}

However, using React and TypeScript, I want to do something like this:

const Colored = ({ color }: { color: "yellow" | "red" ) => (
    <div color={color}>
        { color }
    </div>
);

However, I can't add abritrary props to div!! so we could do exactly the same as the above, but instead

<Colored color="red" />
<Colored color="yellow" />

How can I do something like this? Additionally, should I even be doing this? Is there a better way of doing this in React?

CodePudding user response:

In this case using the type React.HTMLAttributes<HTMLDivElement> you can pass additional properties to the DIV mantaining your component Colored.

type IColoredProps =  { color: "yellow" | "red" } & React.HTMLAttributes<HTMLDivElement>
     
const Colored: FC<IColoredProp> = (props) => (
    <div {...props}>
        {props.color}
    </div>
);

Now the color is mandatory and can only be "red" or "yellow", and you can pass the rest of properties a normal div can have.

<Colored style={{ fontSize: "25px" }} color="red"/>

CodePudding user response:

I created a codeSandBox example for you :

  • instead of <Colored text="red" /> you should use <Colored color="red" />
  • Related