I have a navbar component that I have created using Styled Components. I would like to create some props that change the background-color and/or text color.
For instance: <Navbar dark>
should have the following CSS:
background: #454545;
color: #fafafa;
Whereas <Navbar light>
should be the opposite:
background: #fafafa;
color: #454545;
If, however, neither prop is used, then I want to have a default background and text color -- say (for demo purposes), something like this:
background: #eee;
color: #333;
Now, my question is how to set this up in Styled Components.
I can do the following:
background: ${props => props.dark ? #454545 : '#eee'}
background: ${props => props.dark ? #fafafa : '#eee'}
background: #eee;
And something similar for color.
But this is redundant and not very elegant. I would like some sort of if/else statement:
background: ${ props => {
if (props.dark) { #454545 }
elseif (props.light) { #fafafa }
else { #eee }
}
But I don't know how to set something like that up in Styled Components.
Any suggestions?
Thanks in advance.
This is the solution I ended up using:
export const Navbar = styled.nav`
width: 100%;
... // rest of the regular CSS code
${props => {
if (props.dark) {
return `
background: ${colors.dark};
color: ${colors.light};
`
} else if (props.light) {
return `
background: ${colors.light};
color: ${colors.dark};
`
} else {
return `
background: ${colors.light};
color: ${colors.dark};
`
}
}}
`