What is the best way to integrate SVGs into a React project after transitioning from Vanilla JavaScript?

I am currently diving into an Advanced CSS course that explores the implementation of SVG's. However, the approach involves Vanilla JS whereas I aim to incorporate it into a React project.

When using Vanilla JS to embed an SVG into a button, you typically write code like this:

<button class="search__button">
    <svg class="search__icon">
        <use
            xlink:href="img/sprite.svg#icon-magnifying-glass"
        ></use>
    </svg>
</button>

Nevertheless, this code does not function properly within a React application. It is known that xlink:href needs to be modified to xlinkHref, and "class" should be changed to "className". Despite these adjustments, the SVG still fails to render.

What could be causing this issue and what modifications are necessary for successful SVG rendering in React?

Answer №1

While I may not have a lot of experience with Svgs, one effective method to accomplish this is by converting the svg into a reusable component.

function SVG(props){
    
      return <svg> //insert the raw svg code here </svg>
    }

export default SVG; 

Next, import the SVG component into the desired file like this:

import SVG from 'insert path to SVG component function here' ;

Once imported, you can utilize it as follows:

<button> 
<SVG/>
</button>

Alternatively, you can directly import the svg as if it were a regular image:

import Svg from 'insert path to raw svg location (not the component above)'

and then use it in your code like so:

<img src={Svg}>

Answer №2

I have come across two rather simple solutions that seem to do the job, although I can't guarantee they are the most efficient.

If you have any other suggestions or improvements, please feel free to share them. If there is a superior solution, I will give it the recognition it deserves :)

Solution 1

One approach is to use the SVG file as the source for an

<button className="search__button">
    <img className="search__icon" src="/img/SVG/magnifying-glass.svg" />
</button>

This method stood out to me as the most effective one at first, but I encountered some issues with it initially. In my React project utilizing bundle.js and webpack, the path ended up being different than expected. So if you opt for this solution and encounter a broken image, try experimenting with the path. I went through several variations of the path, including starting with ../, and eventually, found a path that worked.

Solution 2

Alternatively, you can directly insert the SVG code into your JSX code. It may not be the most elegant solution, but it gets the job done.

<button className="search__button">
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20">
<title>magnifying-glass</title>
<path d="M17.545 15.467l-3.779-3.779c0.57-0.935 0.898-2.035 0.898-3.21 0-3.417-2.961-6.377-6.378-6.377s-6.186 2.769-6.186 6.186c0 3.416 2.961 6.377 6.377 6.377 1.137 0 2.2-0.309 3.115-0.844l3.799 3.801c0.372 0.371 0.975 0.371 1.346 0l0.943-0.943c0.371-0.371 0.236-0.84-0.135-1.211zM4.004 8.287c0-2.366 1.917-4.283 4.282-4.283s4.474 2.107 4.474 4.474c0 2.365-1.918 4.283-4.283 4.283s-4.473-2.109-4.473-4.474z"></path>
</svg>
</button>

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

Retrieve the entire webpage, not just the segmented Ajax response

Currently, I'm in the process of developing a web application that utilizes Javascript on the client side along with the Jquery Library and PHP on the server side. My implementation heavily relies on AJAX functionality, and I have purposely avoided us ...

Best Practices for Closing MySQL Connections in Node.js

Currently, I am working on a project using Node.js in combination with Express and MySQL. My main concern at the moment is regarding the closing of the connection to MySQL. The code snippet for this operation is provided below: iniciarSesion(correo_el ...

JavaScript loop that removes the first matching element in an array

My array of Exclusions is structured as shown below: Exclusions: [ID:"233242", Loc:"West", ID:"322234" , Loc:"South"] Within my Object, I have a nested array of objects that resembles: Schools : [ O: [ ID:"233242" ] , 1:[ ID:"233242"] , 2: [ID :"954944" ...

Error in inferring argument types for a generic interface function in Typescript

Unique interface export interface DataService { getByTypeId<T extends number | string>(id: T): Promise<SomeType>; } Additionally, the implementation export class BService implements DataService { async getByTypeId(id: number): Promise&l ...

Can `display:none` and `display:inline` be used to reveal a hidden element nested within another?

If I want to change the appearance of certain classes with CSS, I can do so in the following code: <ul class="productText"> <li>Thycotic Secret Server <span id="headerControl_VersionNumber" class="VersionNumber">8.8</span>< ...

Expanding the dropdown menu depending on the selection of the radio button

I am looking to implement a feature where the drop-down option is displayed or hidden based on the selection of a radio button in AngularJS. If the "Overall Company" radio button is selected, then the drop-down element should not be shown. If the "Demogra ...

A guide to using jqGrid: Retrieve the value of a particular cell by double clicking on a row

Is there a way to implement a feature where users can double click on any part of a row and have it open a new HTML page based on the specific content in a cell? For example, I have a table with different counties in New York listed in separate rows: Coun ...

What is the necessity of the contentLabel prop in react-modal?

Recently, I've been encountering a warning message related to my react-modal components: Warning: Failed propType: Required prop contentLabel was not specified in Modal. While this warning doesn't impact the functionality of the modal, it d ...

selectors that seem to be floating

I attempted to line up certain selectors horizontally on the same line using float:left. However, it did not work as expected! Could someone please assist me with this issue? http://jsfiddle.net/6YKhT/ ...

Is it possible to trigger the onNewRequest property when the onBlur event is fired for AutoComplete in Material-UI?

Currently, I am utilizing Material-UI and making use of the onNewRequest property in the AutoComplete field. However, the onNewRequest only triggers when Enter is pressed or when a value is selected. I am interested in calling the onNewRequest even when ...

Having trouble with Bootstrap form-inline stacking issue, any tips on how to stop them from stacking?

I've created a simple test navbar with a search input box and search button using the Bootstrap class form-inline. However, the search button is appearing below the search input, even though there is enough space available. You can view the codepen he ...

Is there a way to transmit a video mediastream from ReactJS to Python via Websocket?

I am trying to figure out how to send a user's video stream as an array buffer to Python using websockets. I am having trouble understanding how to convert the getUserMedia stream into an array and then send it to Python using fastapi websocket. Belo ...

VeeValidate fails to validate input fields in a form that is constantly changing

My goal is to create dynamic forms with validations using veeValidate in Vue.js. I am attempting to achieve this by storing an array of objects within the component's data. For instance: data(){ return{ inputs: [ { id: 1, lab ...

The attempt to create a React app was unsuccessful after running the command `npm init react-app my-app

Can anyone assist me in resolving this error? https://i.sstatic.net/mXA3o.png I utilized npm to generate the React application. Unfortunately, utilizing npx create-react-app is not an option as it takes over 40 minutes to create the app even with a high- ...

Present the grid card elements in a seamless and uniform manner, eliminating any gaps

My goal is to display card elements of the same category evenly and continuously within a grid without line breaks. In the current layout, there are inconsistencies where certain cards have more space between them than others, causing some elements to sta ...

The outcome of the method is not being displayed

I have an issue with updating the value of an array method in an HTML file using the p tag. The problem is that even though the method returns the value, the HTML doesn't update to reflect the new value. Strangely, when using console.log, the value ap ...

Updating parent data after filtering props in a child component: A comprehensive guide

After filtering the month in the child component, I am trying to update the data in my parent component. However, when I attempt to download excel data using vue-json-excel, the filtered month in the parent component refuses to update. I have experimented ...

Submitting forms that contain files using jQuery and AJAX

Despite searching through numerous questions on this topic, I have yet to find a solution to my specific issue. My objective is to successfully submit an entire form, potentially containing files as well. The code I currently have is not working: $(target ...

Searching in sequelize for a specific date using a clause

Operating System: Linux (Lubuntu) Programming Language: Javascript (Node js) Framework: express js Database: mysql "data" represents a Date field from the "activitat" table Upon running this query using Sequelize.js models.TblActivitat.findAll( ...

Leverage the Nuxeo client SDK with Angular 6 for seamless integration with RESTClient in

Looking to integrate the Nuxeo ClientSdk with my Angular 6 client to consume its REST API, but facing issues due to the lack of typescript definitions for this JavaScript package. Tried importing the library into my project using the following code snippe ...