Passing objects as props to JSX React

Total
0
Shares

In React we get different needs like this one. Here we are trying to pass an object as props to JSX. You might want to do it in two ways. Either passing the whole object as a single props or break the key-value pair as separate props. Let’s see how we can do this.

Code Example

Suppose we have an object –

const superHeroObj = {'name': 'Ironman', 'weapon': 'Suit'}

Now, we want to pass this object as prop to some of our component. As we said in the first paragraph, we can either pass the whole object as a single prop or we can have separate props for all keys.

To pass whole object, we can do this –

return(
  <SuperHeroComponent superHeroObj={superHeroObj} />
)

We can access the object values using props.superHeroObj in SuperHeroComponent.

export default function SuperHeroComponent(props){
  return(
    <div>
      <p>SuperHero Name: {props.superHeroObj.name}</p>
      <p>SuperHero Weapon: {props.superHeroObj.weapon}</p>
    </div>
  )
}

To pass values as separate props, use spread operator

return(
  <SuperHeroComponent {...superHeroObj} />
)

The spread operator will spread out all the key-value pair of object and make them separate props. Internally, the above code will become this –

return(
  <SuperHeroComponent name={'Ironman'} weapon={'Suit'} />
)

To access these props in component, we no longer need to call props.superHeroObj as we are getting the values separately.

export default function SuperHeroComponent(props){
  return(
    <div>
      <p>SuperHero Name: {props.name}</p>
      <p>SuperHero Weapon: {props.weapon}</p>
    </div>
  )
}

    Tweet this to help others

Live Demo

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

.map is not a function

map() can only be used with Arrays. So, if you are getting error .map is not a function, you are probably using it on either the objects or other variables…
View Post