A guide on incorporating an unflattened SVG file into a React component

I am having trouble embedding an SVG file in a React component because it seems to appear flattened. Is there a way to display it as pure SVG?

Please take a look at where it is posted:

Also, this is how it's supposed to be viewed:

This is the method I have tried:

import WordCloud from '../assets/images/landing/wordcloud_ahmet.svg';

Any help would be greatly appreciated.

Answer №1

When it comes to inline simple SVG, you'll need to convert all the style attributes inside svg into JSX type styles attributes and classes into classNames.

This method works well for smaller SVG files.

Check out this example on CodePen: Inline SVG

function SvgWithXlink (props) {
    return (
        <svg
            width="100%"
            height="100%"
            xmlns="http://www.w3.org/2000/svg"
            xmlnsXlink="http://www.w3.org/1999/xlink"
        >
            <style>
                { `.classA { fill:${props.fill} }` }
            </style>
            <defs>
                <g id="Port">
                    <circle style={{fill:'inherit'}} r="10"/>
                </g>
            </defs>

            <text y="15">black</text>
            <use x="70" y="10" xlinkHref="#Port" />
            <text y="35">{ props.fill }</text>
            <use x="70" y="30" xlinkHref="#Port" className="classA"/>
            <text y="55">blue</text>
            <use x="70" y="50" xlinkHref="#Port" style={{fill:'blue'}}/>
        </svg>
    );
}


ReactDOM.render(<SvgWithXlink fill="violet" />, document.querySelector('body > div'));

For more information, refer to this question: embedding-svg-into-reactjs

If your SVG file is large, consider flattening it before importing. This makes it easier to edit in the future using any SVG editor.

Converting the SVG file into JSX style may restrict its compatibility with SVG editors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript Function or Object: A Guide to Returning

Currently, my code is functioning as expected. However, I am curious if there is a way to modify my function so that it can be declared as an object even when no parameters are provided. Below is the mixin function in question: import Page from "@/models ...

I encountered an issue where the font awesome icons failed to load on my website

My website is experiencing an issue where all the Font Awesome icons are not displaying despite having added Font Awesome. Here is the link to my site: https://i.stack.imgur.com/RcNtv.png .login-top .lg-in::before { font-family: "Fontawesome"; ...

Improving the functionality of the search box

I'm currently working on a map project using the google-maps-react API within React. I've encountered an issue where typing characters in the search box doesn't filter my list or markers. Any suggestions on how to tackle this problem? Below ...

Dealing with null values in nested arrays in Vue

Coming from a background in Ruby code, I have a question for you. I recently received this API response: [{:id=>"61b79d02a0f6af001374744e", :name=>"Waffle Crewneck", :code=>"FW22KS000", :result=>{"status ...

The positioning attribute and flexible height in CSS are essential for creating dynamic

My goal is to create a layout with 3 DIVs inside a container, similar to table rows. top {height = 100px} / middle {height = dynamic} / bottom {height = 100px} I am trying to figure out the best approach to make the height of the middle div dynamic whi ...

What CSS selector should I apply to create a circular profile image for Buddypress users?

In my current WordPress project, I am utilizing the BuddyPress, WooCommerce, and WC Vendors plugins for enhanced functionality. To personalize each vendor's product listings, I decided to display their BuddyPress profile picture alongside their produ ...

"Use jQuery to target the first child element within a parent element that has a specific class

Is there a way to choose only the first child of a specific parent class with a certain class for the purpose of clone()? <div class="sector_order"> <div class="line_item_wrapper"> SELECT THIS DIV </div> <div class=" ...

Tips for overcoming a challenge with a promise of $q

Currently in my AngularJS project, I am utilizing $q for promises and feeling a bit overwhelmed with the usage. How can I resolve this promise-related issue? My goal is to either return the user when isLoggedInPromise() is triggered or provide a response ...

Can you explain why the .js code is causing such high CPU usage in popular video players?

Why is the .js code running continuously even when the video is paused and there is no user interaction? I observed this phenomenon on a Windows 10 Atom Tablet, particularly when in energy-saving mode. The CPU usage for video playback and decoding almost ...

Is the Mini Cart button in Woocommerce not aligned properly?

My website was functioning perfectly until yesterday. However, after updating some plugins, the Mini Cart dropdown button started to display in a weird and misaligned manner. https://i.sstatic.net/SsZee.jpg Prior to the plugin updates, the button had the ...

Node.js is facing a problem with its asynchronous functionality

As a newcomer to node, I decided to create a simple app with authentication. The data is being stored on a remote MongoDB server. My HTML form sends POST data to my server URL. Below is the route I set up: app.post('/auth', function(req, res){ ...

Struggling with setting up and installing the MDX transformer plugin (as well as its dependencies) on a Gatsby site

Task: Currently working on setting up a basic blog using Gatsby Results: Expected Result: Following the tutorial guide as expected Actual Result: Encountering Dependency tree error at certain steps & also receiving a warning message stating 34 vulnerab ...

Unable to call a basic object's prototype method

Just starting out with node and feeling like I might be overlooking something simple. In my model file, I have a class that creates new object instances in the following way: const mongodb = require('mongodb'); const getDb = require('../util ...

Struggling with setting up Role-Based Access Control (RBAC) with cookie authentication in React

I've been working on incorporating Role Based Access Control into a React app using cookies, but I'm struggling to understand its use. The idea was to create a context that retrieves the data stored in the cookie through a specific API endpoint d ...

Differences between <StaticQuery /> and page query in Gatsby: Which one should you choose?

In Gatsby, a page query is typically requested at the parent level and then passed down as props to the child components. On the other hand, you can use <StaticQuery /> or the useStaticQuery hook when you are within a component and need to fetch data ...

"Revitalizing only the metabox on a WordPress product page - a step-by

When navigating through my wordpress admin panel and accessing the product page, I encounter an issue with the product categories metabox. After adding a new category, the list does not update automatically and requires a full page refresh for the changes ...

Utilize AngularJS to effortlessly filter and search data

I am facing an issue with my AngularJS code for searching text. The rows in the table are not being displayed properly and the search functionality is not working effectively. <html ng-app="myModule"> <head> <title>TODO suppl ...

Issue with Backbone collection not being updated despite making a JSONP request

Recently, I delved into the world of Backbone.js and currently, I am immersed in developing an app using Brunch that makes a JSONP request to an external API for populating my collection and models. Despite following guidance from previous posts (here and ...

Getting Errors When Retrieving Data with Apostrophe Symbol ' in Node.js

I am currently developing a Next.js API page to extract data from a series of URLs. Interestingly, the URLs containing an apostrophe character ' fail to return any data, while those without it work perfectly fine. Surprisingly, when I execute the same ...

The CSS box-shadow property failed to render properly on Internet Explorer and Safari browsers

#keyboard { position: fixed; background: #eee; display: none; border: 1px solid #ccc; border-radius:7px; width: 950px; height: 300px; padding: 5px; cursor: move; background-image:url('BackgroundImage.jpg'); box-shadow: -5px -5px 5px 5px #888; -m ...