I'm about to build a small project in react using styled ponent, however, I have a question for using this package. I would like to create a styled ponent 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 ponent ? In css there are two different classes, but in styled ponent i don't know.
Thank you.
I'm about to build a small project in react using styled ponent, however, I have a question for using this package. I would like to create a styled ponent 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 ponent ? In css there are two different classes, but in styled ponent i don't know.
Thank you.
Share Improve this question asked Nov 14, 2020 at 20:51 user4671973user4671973 3- I think you need to think about the bined styles of both classes, and use props to adjust your styling dynamically. What do these classes do in normal CSS? – BlackMath Commented Nov 14, 2020 at 21:44
-
we can get @Aib Codes Daily example,
.search-input { background-color: blue; } .search-input-small { color: white; }
– user4671973 Commented Nov 15, 2020 at 10:52 -
First define
const SearchInput = styled.div` backgroundColor: blue;`
and then defineconst SearchInputSmall= styled(SearchInput)` color: white;`
and use theSearchInputSmall
styled ponent in place of the div with multiple classes. – BlackMath Commented Nov 15, 2020 at 13:45
2 Answers
Reset to default 6There are a few ways to do this. For example, you could run with the base styling on a styled ponent 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-ponents, you can go with a similar format.
Here we are creating a styled ponent named Div
, within the styled ponent 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 ponent 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.