Michael
Michael

Reputation: 443

Passing in same prop to multiple styled components

I have 3 React Components that are all being passed the same prop isNewListingsHeader. I am using Styled Components for CSS styling. I'm wondering if there is a cleaner way of passing this prop into the 3 different styled components SortBarWrapper, SortOptionsWrapper, and SortOptionsWrapper so that I don't have to define isNewListingsHeader each time.

// Styled Components
const SortBarWrapper = styled.div`
   position: relative;
   ${props => !props.isNewListingsHeader && `
     height: 100px;
  `}
`

const SortLineWrapper = styled.div`
   width: 100%;
   ${props => !props.isNewListingsHeader && `
     position: absolute;
     bottom: 0;
   `}
`

const SortOptionsWrapper = styled.div`
   box-sizing: border-box;
   ${props => !props.isNewListingsHeader && `
     padding-bottom: 24px;
     padding-top: 32px;
   `}
`


 render () {
   return (
     <SortBarWrapper isNewListingsHeader={this.props.isNewListingsHeader}>
       <SortLineWrapper isNewListingsHeader={this.props.isNewListingsHeader}>
         <SortOptionsWrapper isNewListingsHeader={this.props.isNewListingsHeader}>
           // Display Sort Options
         </SortOptionsWrapper>
       </SortLineWrapper>
     </SortBarWrapper>
   )
 }

Upvotes: 1

Views: 504

Answers (2)

Ravi
Ravi

Reputation: 49

We can use context api. Create a provider and Consumer. Wrap all the components inside the provider, Provider accepts a value prop and the data in this prop is available to all the child consumers. And can use them inside consumer.

“Why you should consider the new Context API in React? — A deep dive” by Mahesh Haldar https://link.medium.com/zrYj36RnhU

Upvotes: 0

thatgibbyguy
thatgibbyguy

Reputation: 4103

What you are doing is not incorrect but I can understand you wanting to DRY up your code. I am not going to say what is the "right" way because there is technically no correct way, just ways you prefer to do it based on your stack (for example, are you using Redux or any other state management?).

This medium post covers several methods of deep nesting components.

Explore that and pick which works for you. But for the sake of this conversation - you are doing it correctly and in the "React way."

Upvotes: 1

Related Questions