I'm about to build a small project in react using styled component, however, I have a question for using this package. I would like to create a styled component that brings together several classes but I don't know how to do, for example :
<div class="search-input search-input-small">
How to turn it into a styled component ? In css there are two different classes, but in styled component i don't know.
Thank you.
There are a few ways to do this. For example, you could run with the base styling on a styled component and then "upgrade that with the additional styling.
const Div = styled.div`
/// styles for className -> search-input
}`
const SmallDiv = styled(Div)`
/// styles for className -> search-input-small
`
Also, if you know SASS you can structure your CSS with nesting using &. e.g.
const Div = styled.div`
.search-input {
//CSS
&-small {
//CSS
}
}
`
With styled-components, you can go with a similar format.
Here we are creating a styled component named Div, within the styled component I've declared classes .search-input and .search-input.search-input-small to style the div from your example.
The Div is being treated as a parent container.
const Div = styled.div`
display: flex;
background-color: black;
.search-input {
background-color: blue;
}
.search-input.search-input-small {
color: white;
}
`;
We call the newly created styled component like this:
export default function App() {
return (
<Div>
<div className="search-input search-input-small">Hello</div>
</Div>
);
}
As you can see the <div class="search-input search-input-small"> from your example is a child to the parent Div. The parent Div does not require styles but I have included them for this example.
Also here is a codesandbox with a working example.
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