woopsie
woopsie

Reputation: 95

Passing and using props in React

Say I had the following

const Obj = [
     {
          name: 'a'
     },
     {
          name: 'b'
     }
]

const RenderSomeObj = props => {
     console.log('props', props)
     return null
}

When I go to render it with

{Obj.map((item, index) => (
    <RenderSomeObj props={item} />
))

It comes out as props: props: {}. how can I get it as just the object that is item like props: { name: 'a'}? eg.

I want props to be

     {
          name: 'a'
     }

not

     props: {...}

Upvotes: 0

Views: 36

Answers (2)

samhodev
samhodev

Reputation: 328

This happens because the attribute props is regarded as a JSX attribute. Please take a look on the react-native documentation

When React sees an element representing a user-defined component, it passes JSX attributes and children to this component as a single object. We call this object “props”.

In here

const RenderSomeObj = props => {
     console.log('props', props)
     return null
}

props is the single object of the JSX attributes and children to this component.

Therefore, to get what you want, simply modify your component as below

 const RenderSomeObj = props => {
     console.log('props', props.props)
     return null
  }

Upvotes: 0

Todd Skelton
Todd Skelton

Reputation: 7239

Use the spread operator.

{Obj.map((item, index) => (
    <RenderSomeObj {...item} />
))

Upvotes: 5

Related Questions