Home > database >  React - functional component container
React - functional component container

Time:11-09

I would like to create a container component in my application. I don't know if this is possible or if it's a good idea at all. I would be so very comfortable.

From this:

export default function App(){
    return(
           <div className={styles.CardsContainer}>
                <CardPrice price={700}/>
                <CardPrice price={3000}/>
                <CardPrice price={5000}/>
          </div>
    )
}

I want to do it:

export default function App(){
    return(
           <CardsContainer>
                <CardPrice price={700}/>
                <CardPrice price={3000}/>
                <CardPrice price={5000}/>
          </CardsContainer>
    )
}


I do this in CardsContainer:

export default function CardsContainer(){
    return(
           <div className={styles.CardsContainer}>

           </div>
    )
}

Obviously it doesn't work) But I don't know how to wrap properly. I don't want to put components with CardPrice in a CardContainer component. I want to wrap in App component

CodePudding user response:

u can use this, but you will need take de props.chidlren inside of the container.

export default function CardsContainer({children}){
return(
       <div className={styles.CardsContainer}>
         {children}
       </div>
)

}

but i think will be better if u use styled component to create de container

CodePudding user response:

You need to pass the elements as children to the CardsContainer and in CardsContainer component you can access it using the children prop. For a better understanding, you could refer these docs: https://reactjs.org/docs/composition-vs-inheritance.html#containment

export default function CardsContainer({children}){
return(
       <div className={styles.CardsContainer}>
         {children}
       </div>
)
  • Related