Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering an SVG from an object

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

  • {$$typeof: Symbol(react.forward_ref), render: ƒ}$$typeof: Symbol(react.forward_ref)render: ƒ SvgSanfrancisco({ title, titleId, ...props }, svgRef)displayName: (...)get displayName: ƒ ()set displayName: ƒ (name)arguments: (...)caller: (...)length: 1name: "set"prototype: {constructor: ƒ}proto: ƒ ()[[FunctionLocation]]: react.development.js:1401[[Scopes]]: Scopes[4]proto: Object...*

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>
                            );
                        })}
like image 689
Chidex Avatar asked Mar 20 '26 13:03

Chidex


1 Answers

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>
   );})}
like image 79
lissettdm Avatar answered Mar 23 '26 04:03

lissettdm