Reputation: 179
I have a React project I'm working on and I'd trying to render an SVG from an array of objects. I however get an error whenever i try accessing the SVG from the map method. Is there a better way to go through the process that I'm missing. For context:
locations: [
{ svg: SanFrancisco, city: "San Francisco, CA", number: 54 },
{ svg: Redwood, city: "Redwood City, CA", number: 1 },
{ svg: NewYork, city: " New York, NY", number: 17 },
{ svg: Portland, city: "Portland, OR", number: 10 }
]
The SVGs have already been imported as React components here.
The usage in jsx:
{locations.map((location) => {
return (
<a href="#">
{" "}
<div className="locations-card card">
{location.svg}
<h2>{location.city}</h2>
<p>{location.number} openings</p>
</div>
</a>
);
})}
logging location.svg to the console returns an object of this nature
Is it possible to access the svg icon itself via the object?
Edit: per a suggestion, the code below did the trick
{locations.map((location) => {
return (
<a href="#">
{" "}
<div className="locations-card card">
<location.svg/>
<h2>{location.city}</h2>
<p>{location.number} openings</p>
</div>
</a>
);
})}
Upvotes: 3
Views: 2475
Reputation: 13078
If the svg property is a react component
:
{locations.map((location) => {
const Svg = location.svg; // --> get the component
return (
<a href="#">
{" "}
<div className="locations-card card">
<Svg />{/* --> render it*/}
<h2>{location.city}</h2>
<p>{location.number} openings</p>
</div>
</a>
);})}
Upvotes: 6
Reputation: 1058
Try to save the component itself in the object. e.g
{ svg: < SanFrancisco/>, city: "San Francisco, CA", number: 54 },
and then render {location.svg}
Upvotes: 0