Commando
Commando

Reputation: 358

How to create nested components?

I'm trying to build a component that has a few components nested inside of it with props.

Something like that:

<DivWithBlueBackground>
  <Title />
  <Sometext theColor="white">This text is white</Sometext>
</DivWithBlueBackground>

How can I write Sometext component? Tried that but not sure where to define props for Sometext:

const DivWithBlueBackground = ( {children} ) => ( <div style={{ backgroundColor: 'blue' }}> {children} </div> );
const Title = () => <div>The title </div> ;
const Sometext = ( props, {children} ) => <div style={{ color: props.theColor }}> {children} </div>

Upvotes: 0

Views: 160

Answers (3)

lala
lala

Reputation: 1439

sending props to a component is just like what you already did or have:-

<DivWithBlueBackground>
  <Title />
  <Sometext 
    theColor="white" 
    otherProp="otherProp"
  >
    This text is white
  </Sometext>
</DivWithBlueBackground>
  1. You can receive props as props or whatever args you wanna put:-
const Sometext = (props) => {
  return (
    <div style={{ color: props.theColor }}>Some content...</div>
  )
}
  1. Or you could do props destructuring:-
const Sometext = ({ theColor, otherProp }) => {
  return (
    <div style={{ color: theColor }}>Some content of {otherProp}</div>
  )
}

Any of above methods will work.

Upvotes: 0

Someone Special
Someone Special

Reputation: 13588

following comment.

const DivWithBlueBackGround = ({children}) => {
     return (<div>{children}</div>)
}

Child Component

const ChildComponent = (props) => {

  return ( <div style={{ backgroundColor: props.theColor }}></div>

}

Passing props to children.

const App = () => {

return (<DivWithBlueBackGround>
           <ChildComponent theColor="blue" />
           <ChildComponent theColor="red" />
        </DivWithBlueBackGround>)
}

you can name it theColor or anything you want, and they will be accessible by props in ChildComponent

Upvotes: 1

user14361391
user14361391

Reputation:

Here you go, you should use string interpolation to define props explicitly.

const DivWithBlueBackground = ( {children} ) => (<div style={{ backgroundColor: 'blue' }}> {children} </div> );
const Title = () => <div>The title </div> ;
const Sometext = ( props, {children} ) => <div style={{ color: `${props.theColor}` }}> {children} </div>

Upvotes: 0

Related Questions