user3598632
user3598632

Reputation: 11

use of {children} in a react component

I am new to React and i am here with a very basic query. What's the use of {children} in the following react code.

const Store = ({children}) => {
    const [state, setState] = useState(initialState)
    return(
        <Context.Provider value={[state, setState]}>
            {children}
        </Context.Provider>
    )
}

Upvotes: 0

Views: 7049

Answers (4)

Antenaina
Antenaina

Reputation: 164

As written in the React documentation about Composition vs Inheritance, the children prop is a special prop that is used to pass directly children element into the output of the parent element.
In your example, using the Store component like this:

<Store>
    Hello!
</Store>

has the same effect as:

const Store = () => {
    const [state, setState] = useState(initialState)
    return(
        <Context.Provider value={[state, setState]}>
            Hello!
        </Context.Provider>
    )
}
// then call it like:
<Store />

or:

const Store = ({input}) => {
    const [state, setState] = useState(initialState)
    return(
        <Context.Provider value={[state, setState]}>
            {input}
        </Context.Provider>
    )
}
// the call it like
<Store input="Hello!" />

Upvotes: 0

seagullsofskynet
seagullsofskynet

Reputation: 28

Children are the components nested in between your component's open and close tag. For example:

 <Header>
 <Menu />
 </Header>

In this case, Menu would be a child of Header.

In the slightly more complex example in your code, the children would be whatever you nest in Store. In this case you are using context so that any child of those children can also access the values passed into Context.Provider. The point of this is to avoid "props drilling" - but we're getting beyond the scope of your question now!

Upvotes: 1

Mahmood Najafi
Mahmood Najafi

Reputation: 44

children is a reserved word that returns all children you pass between your opening and closing component element. visit this page for more info: https://reactjs.org/docs/composition-vs-inheritance.html

Upvotes: 1

Shubham Verma
Shubham Verma

Reputation: 5054

Passing components as a body. In your case if you write

<Store>
  <Header/>
<Footer/>
//any data here
</Store>

It will automatically place here:

<Context.Provider value={[state, setState]}>
            {children} <-here you do need to define again
        </Context.Provider>

Upvotes: 1

Related Questions