How to keep custom attribute in styled component?

695 Views Asked by At

I created a simple styled component with a custom property test, but when rendered, the test property just did not appear in the div dom, what happened?

const StyledDiv = styled.div<{
    test?: boolean;
}>`
    color:red;
`;
//in render function...
<StyledDiv test>it's just test</StyledDiv>

enter image description here

1

There are 1 best solutions below

3
On

In React boolean value is not passed to the dom element in means that test or test={true} will not be available to the dom. It only supports three types of string, number and object and it will convert those to string so all you need to do is change it too test="" and it will work.

If you are looking to access the prop test in your component you need to do something like this:

const StyledDiv = styled.div`
    color: ${({test}) => test ? 'red' : 'blue'};
`;