Passing props from parent styled-component to immediate child styled-component.
See original GitHub issueI am currently trying to create a grid system using styled components and I was wondering if it is possible to pass props
from a parent styled to a child component. See below for example.
const Parent = styled('div')`
background: blue;
`;
const Child = styled('div')`
margin: ${props => props.gutter ? '10px' : null ;}
`
render() {
return(
<div>
<Parent gutter>
<Child />
</Parent>
</div>
)
}
Hope the example makes sense. Is it possible at all to achieve this?
Thanks in advance 👍
Issue Analytics
- State:
- Created 6 years ago
- Reactions:2
- Comments:7 (2 by maintainers)
Top Results From Across the Web
How to access child's props from parent's styled-component?
Short answer: You have to pass the parent prop to the child component. In a parent component <Wrapper /> you would have to...
Read more >styled-components: Advanced Usage
This function will receive the parent theme, that is from another <ThemeProvider> ... A theme can also be passed down to a component...
Read more >Styled-Components: Extending Children
Even when styled-components often export different variations of the component it can still be useful to control the styles from the parent.
Read more >How To Use React Styled Components Efficiently
Styled -components: Dynamic Styling with Props Passed ... styles that enable children element to be styled via their parent styled component.
Read more >8 awesome features of styled-components
Props can be passed to styled components just as they are with regular React components (class or functional). This is possible because styled ......
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
This is not specific to styled-components, but a more general React question. I wrote a lengthy blogpost about exactly this topic, what you’re looking for is detailed in the last section: http://mxstbr.blog/2017/02/react-children-deepdive/
You’d likely do something like this:
All of that being said, if you’re not super set on using JS, you could also just use CSS for this, which would be easier:
This has nothing to do with
styled-components
. with theParent
component you can access it’sprops.children
and pass them w\e you like while rendering.