Passing/Accessing props in stateless child component

Paulos3000 picture Paulos3000 · Jan 23, 2017 · Viewed 26.7k times · Source

I know you can pass all a react components props to it's child component like this:

const ParentComponent = () => (
   <div>
     <h1>Parent Component</h1>
     <ChildComponent {...this.props} />
   </div>
)

But how do you then retrieve those props if the child component is stateless? I know if it is a class component you can just access them as this.prop.whatever, but what do you pass as the argument into the stateless component?

const ChildComponent = ({ *what goes here?* }) => (
   <div>
      <h1>Child Component</h1>
   </div>
)

Answer

Shubham Khatri picture Shubham Khatri · Jan 23, 2017

When you write

const ChildComponent = ({ someProp }) => (
   <div>
      <h1>Child Component {someProp}</h1>
   </div>
)

From all the props that you are passing to the childComponent you are just destructuring to get only someProp. If the number of props that you want to use in ChildComponents are countable(few) amongst the total number of props that are available, destructuring is a good option as it provides better readability.

Suppose you want to access all the props in the child component then you need not use {} around the argument and then you can use it like props.someProp

const ChildComponent = (props) => (
   <div>
      <h1>Child Component {props.someProp}</h1>
   </div>
)