Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I set a option to selected using styled-components?

How do I use styled-component attributes to set the selected property of my styled option so that the option is selected within the select element depending on whether or not the isSelected property is truthy?

Right now I have this:

export const MyOption = styled.option.attrs(props => ({
    selected: {props.isSelected ? "selected" : ""}
})``;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you’ve got there is actually almost exactly how you do it.

The only thing you need to change is that you are setting the attrs selected to an object using curly-brackets {} when you should be using normal brackets () to do the logic.

export const MyOption = styled.option.attrs(props => ({ 
    selected: (props.isSelected ? "selected" : ""),
 }))``;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading