Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - Conditional svg rendering in React

I'm working in React and have an object that looks something like this:

[{ 
"title": "instagram", 
"href": "http://instagram.com"
"class": "instagram"
},
{ 
"title": "facebook", 
"href": "http://facebook.com"
"class": "facebook"
},
{ 
"title": "twitter", 
"href": "http://twitter.com",
"class": "twitter"
},
{ 
"title": "twitch", 
"href": "http://twitch.com"
"class": "twitch"
}]

and some variables that have an svg path like this...

const facebook = <svg path goes here>
const instagram = <svg path goes here>

and so on. My idea was to iterate through the object with the map method, and since the name of the classes is the same of the variables, that the variables content replaced the path and the icon showed, something like this:

 <div>
            {array.map((item, i) =>{
        
                return <div>
                    <svg  width='40' height='40' viewBox="0 0 38.89 38.91"><path class="cls-1" d={item.class} transform="translate(-24 92.04)"/></svg>
                    </div>
            })
            }
        </div>

but the icons aren't showing up. Why isn't the svg appearing? What would be a better solution?

question from:https://stackoverflow.com/questions/65894364/conditional-svg-rendering-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The d attribute defines a path to be drawn.

In your example, you are just assigning a string like "instagram" to the path's d attribute and expecting it to draw the instagram icon.

This won't work because d="instagram" is not a valid svg path command.

If you can edit your data source, why not just add the path there - under the path key in each item in the array?

[
    { 
        "title": "instagram", 
        "href": "http://instagram.com"
        "class": "instagram",
        "path": "<svg path goes here>"
    },
    ...
]

<div>
    {array.map((item, i) => {
        return (<div>
            <svg  width='40' height='40' viewBox="0 0 38.89 38.91">
                <path class="cls-1" d={ item.path } transform="translate(-24 92.04)"/>
            </svg>
        </div>)
    })}
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...