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?
2
Answers
In this case using the type
React.HTMLAttributes<HTMLDivElement>
you can pass additional properties to theDIV
mantaining your componentColored
.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.I created a codeSandBox example for you :
<Colored text="red" />
you should use<Colored color="red" />