I'm having trouble understanding the spread operator when I want to pass all other props to a ponent.
Any help would be appreciated.
import React, { Fragment } from "react";
import SiteCard from "./SiteCard";
const SiteList = ({ sites }) => {
return (
<Fragment>
{sites.map((site) => {
return (
<SiteCard
key={site.login.uuid}
image={site.picture.large}
firstName={site.name.first}
lastName={site.name.last}
city={site.location.city}
country={site.location.country}
sensors={site.dob.age}
otherSiteProps={...site} // how can I pass the site props here?
/>
);
})}
</Fragment>
);
};
export default SiteList;
I'm having trouble understanding the spread operator when I want to pass all other props to a ponent.
Any help would be appreciated.
import React, { Fragment } from "react";
import SiteCard from "./SiteCard";
const SiteList = ({ sites }) => {
return (
<Fragment>
{sites.map((site) => {
return (
<SiteCard
key={site.login.uuid}
image={site.picture.large}
firstName={site.name.first}
lastName={site.name.last}
city={site.location.city}
country={site.location.country}
sensors={site.dob.age}
otherSiteProps={...site} // how can I pass the site props here?
/>
);
})}
</Fragment>
);
};
export default SiteList;
Share
Improve this question
asked Jul 28, 2020 at 11:37
kimo26kimo26
1111 gold badge4 silver badges15 bronze badges
1
-
1
simply write
{site}
instead of{...site}
– Atul Kumar Commented Jul 28, 2020 at 11:40
2 Answers
Reset to default 4You just need to write:
<SiteCard
key={site.login.uuid}
image={site.picture.large}
firstName={site.name.first}
lastName={site.name.last}
city={site.location.city}
country={site.location.country}
sensors={site.dob.age}
{...site} // how can I pass the site props here?
/>
But wait, why you're making so plicated? You can just use:
<SiteCard {...site} />
Now, in your SiteCard ponent use required props.
And if I were you, I would not have separated SiteCard
ponent for this scenario. I would just write:
{sites.map((site) => {
return (
// everything here I will utilize in html.
);
})}
You are almost there with the solution.
You need to pass it as otherSiteProps={{...site}}
.
This is if you want to pass site
as an object to otherSiteProps
property of SiteCard
.
If you want to spread site
and have multiple props for ponent SiteCard
you do it like this:
<SiteCard
key={site.login.uuid}
image={site.picture.large}
firstName={site.name.first}
lastName={site.name.last}
city={site.location.city}
country={site.location.country}
sensors={site.dob.age}
{...sites}
/>
This in case that sites
is an object. If site
is an array, this wont work.