I am just getting started with styled components and want to create variations for things like buttons, navbars, etc.
For instance, I'd like to create a dark version of a navbar (wherein the background color would become dark and the text color light).
What I'd like to do is simply add a prop of dark on a component as follows:
<Navbar dark>...</Navbar>
I'd like to do this as opposed to something like this:
<Navbar type="dark">...</Navbar>
However, I'm not sure how to do this. That is, how do I style an element just by checking if the prop name exists (without passing the prop any values)?
Any ideas? Thanks in advance.
styled-components supports passing props to styled components, and those props can be accessed in the CSS tagged template literal (the CSS inside of the backticks) of the styled component receiving those props.
For example, say that the <Navbar />
in your example is a styled <nav>
element, then we can define <Navbar />
in a way that takes into account a dark
prop:
const Navbar = styled.nav`
background: ${props => props.dark ? 'black' : 'white'}
`
In the example above, we check for the existance of the dark
prop. If it was passed, then we give the component a black
background color. Otherwise (the default), we give the component a white
background color:
<Navbar dark /> // produces component with black background
<Navbar /> // produces the default white background
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With