React is a very dynamic library by nature. Therefore, there are often multiple ways to attain the same result. Today we’ll see how we can pass objects or values as props to components differently.
We have two components named ParentComponent and ChildComponent. We’re going to pass data from the parent to the child component.
Using the spread operator
const ParentComponent = () => {
const person = {
name: 'Shruti',
age: 26,
email: 'Shruti@example.com'
}
return (
<ChildComponent { ...person } />
)
}
const ChildComponent = (props) => {
const { name, age, email } = props
return (
<div>
<p>{name}</p>
<p>{age}</p>
<p>{email}</p>
</div>
)
}
Code language: JavaScript (javascript)
We have an object named person having name, age, and email as properties. We can pass all these properties one by one to another component with the help of the spread operator(…). When we pass these as a spread operator, we can access these values directly from the child component.
Passing each value individually
If we don’t have an object, but rather values in some variables or states, we can pass them individually as follows:
const ParentComponent = () => {
const name = 'Shruti'
const age = '26'
const email = 'Shruti@example.com'
return (
<ChildComponent name={name} age={age} email={email} />
)
}
const ChildComponent = (props) => {
const { name, age, email } = props
return (
<div>
<p>{name}</p>
<p>{age}</p>
<p>{email}</p>
</div>
)
}
Code language: JavaScript (javascript)
Of course, please note that we can name the prop whatever we want in the above case. It doesn’t have to be the same as the passing value name. For example, myName={name} is just as valid as name={name}.
Passing only the required properties of an object
We can also pass only the needed properties of an object. We don’t need to pass the whole object:
const ParentComponent = () => {
const person = {
name: 'Shruti',
age: 26,
email: 'Shruti@example.com',
address: '2 Lane, 3 Street, CA',
gender: 'F',
postalCode: '234DF'
}
return (
<ChildComponent name={person.name} age={person.age} />
)
}
const ChildComponent = ({ name, age, email }) => {
return (
<div>
<p>{name}</p>
<p>{age}</p>
</div>
)
}
Code language: JavaScript (javascript)
In the above example, we have an object named person with 6 properties named name, age, email, address, gender, and postalCode. However, if we need only the name and the age, we don’t need to pass the whole object. This is a better solution than passing the whole object and then only displaying the required properties. It is so because, the child component in this case, won’t occupy memory for the unrequired states.