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>
);
})}
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>
);})}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With