React SVG not displaying on page

I am facing an issue with displaying an SVG in my React application.

Below is the code snippet:

<svg className="svg-arrow">
    <use xlinkHref="#svg-arrow" />
</svg>

 //styling
.user-quickview .svg-arrow {
    fill: #fff;
    position: absolute;
    top: 12px;
    right: 10px;
    -webkit-transform: rotate(90deg);
    transform: rotate(90deg);
}
.svg-arrow {
    width: 4px;
    height: 8px;
    cursor: pointer;
}

The SVG (xlink:href) works perfectly fine in another project that does not use React.

Any suggestions on how to resolve this issue?

Answer №1

In React, SVG images can be displayed without the need for a special link or plug-in. However, there may be situations where an SVG does not show up properly. One reason for this could be that the canvas on which the SVG is drawn is too large and the image created is too small and centered in the middle of the canvas, resulting in excessive white space around the image. To fix this issue, it is important to crop the canvas (known as the viewport) so that the image is positioned close to the edge of the canvas. This means removing any unnecessary white space. By checking the SVG/XML with a text editor, you can determine what the viewport rectangle is set to. Additionally, tools like Illustrator or online SVG editors can be used to visually crop your SVG image.

Answer №2

It's difficult to provide a precise answer without being able to review your components and code. However, have you considered exploring the capabilities of react-svg?
For further insights, you may also find this article helpful.

Answer №3

If you want to generate react components from an SVG icon, simply run

npm "install @svgr/cli --save-dev"
.

After installation, you can easily pass props like fill, height, and width to customize the components. It's a straightforward process.

For a more comprehensive explanation, visit this link.

Answer №4

Here is a code snippet of how I implemented this feature in React:

import React from 'react'
import svg from "../assets/img/sprite.svg";

const Header = () => {
  return (
    <div>
      <button class='search__button'>
       <svg class='search__icon'>
         <use xlinkHref={`${svg}#icon-magnifying-glass`} />
       </svg>
      </button>
    </div>
  )
}

export default Header

If you were to achieve the same result using plain HTML, here is how it would look like:

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

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

Stacking SVG elements can lead to distortion effects

Currently experimenting with the innovative SVG stacking method to integrate multiple icons into a single file, reducing the browser's HTTP requests. The details of this technique can be found in depth here. In essence, it involves placing numerous S ...

Best Practices for Making Remote Requests in Ruby on Rails

Currently, I am creating a Single Page Application using Ruby on Rails for the first time. Although I am still learning, I have set up a side menu with links and a container on the right part of the page to display partial pages. An example of one of my me ...

Issue: Module not found; Typescript error encountered in a react application

I have a load_routes.js file in the node_express folder that is responsible for loading all the routes for my project. Everything was working smoothly until I decided to change the file extension from .js to .ts. Suddenly, I started encountering the follow ...

Access a specific element within an array using Handlebars.js

After converting a CSV to JSON, I have data that looks like this: [["Year","Make","Model","Description","Price"],["1997","Ford","E350","ac, abs, moon","3000.00"],["1999","Chevy","Venture \"Extended Edition\"","","4900.00"],["1999","Chevy","Ventu ...

What are some techniques for breaking down or streamlining typescript code structures?

Within my TypeScript class, I have a skip function. In the interface, I've specified that the data is coming from the backend. Now, on the frontend, I want to be able to rename the backend variables as demonstrated below. There are multiple variables ...

Steps for displaying a deeply nested array and string within an object that is nested further in an array

I've been troubleshooting an issue in my Next.js code where I'm trying to render data called items. My goal is to display the descriptions in an array as a list and display the description that is a string as it is. However, I cannot use the map ...

JavaScript: Utilize MooTools to extract a string containing a specific class and then pass it through a parent function

I am facing a major issue and struggling to find a solution for it. My problem involves returning values, mostly strings, that I can utilize in various contexts. For instance, I need to verify whether something is 0 or 1 in an if/else statement, or insert ...

Getting started with TinyMCE in Nuxt: A step-by-step guide

I need to incorporate this script into my Nuxt code: <script> tinymce.init({ selector: "#mytextarea", plugins: "emoticons", toolbar: "emoticons", toolbar_location: "bottom", menubar: false ...

Only certain fields are returned by JQuery's form serialize() method

Encountering an issue with the serialize() function in jQuery when attempting to submit a serialized form via AJAX. Some of the field values are not being retained. Suspecting a problem with either my HTML structure or jQuery code: <div id="register" ...

Transferring a PHP array to JavaScript using AJAX

I have spent time searching for answers to my issue with no success. My PHP file includes the following array: $data = ['logged' => $_SESSION['loggedin'], 'sessName' => $_SESSION['name']]; echo json_encode($dat ...

Managing PHP multiple follow-up options in HTML select fields

My goal is to design a form that includes multiple follow-up select fields. These fields will be populated from an array with 3 elements: ID, Name, and followingID. The followingID corresponds to an ID in the array, helping us determine the hierarchical la ...

JavaScript's prototypical inheritance model allows objects to inherit properties and

Exploring javascript's prototypical inheritance and object-oriented programming is new to me. I attempted to create a base object called Account and then inherit the CheckingAccount from it. Below is my code snippet. function Account(fName, lName) { ...

Getting the length of child elements in Angular using ngFor loop

Can anyone help me figure out how to check the length of a child element in my Angular *ngFor loop? I am fetching data from a real-time firebase database. What am I doing wrong? Here is the code snippet I am using: <div *ngFor="let event of events"> ...

Simple steps to access a feature on an AngularJS application

I have my angular application stored in a variable (initialized with:) var app = angular.module('app', [...]); Now, I need to access the $timeout service. How can I retrieve this service from it? I am looking for something like: var timeout ...

Capturing the value of an input field within a controller in AngularJS

I have been programming with JSP and Angular JS. Currently, I am faced with a scenario where I need to work with a JSP page containing a hidden input field. To set the value of this input field, I am using a session attribute like so: String policy = (S ...

Locating specific text within an <li> element using the provided value

So, I have this set of words: <li>name</li> <li>myname</li> <li>yourname</li> Then there's also an input box input type="text" value="name" id="the_value" with the value "name", along with a submit button identif ...

Issue encountered when updating npm to version 5.4.2: Unable to locate modules in ./node_modules/react-router-dom

When attempting to update my npm version from 3.10.10 to 5.4.2 and migrate react from 15.3.0 to 16.0, I deleted the node_modules folder and re-ran npm install. However, upon trying to run my application again, I encountered the following error: ERROR in ./ ...

How to pass a single value using onClick event without relying on form submission

I prefer to pass a single value instead of multiple putPriority fetch calls. This value will not be inputted by the user directly, but rather passed through an onClick event. For example, I want the onClick to send a specific number to "status" in the fe ...

I am facing issues with getting the delete function to properly function in my React

Issue with Delete Button Functionality in React While I am able to successfully delete an item using axios call in Postman, implementing the same functionality on the front-end in a React component seems to be causing problems for me. <button onSubmit ...

Looking for a method to incorporate an onclick function into a column for renderCell within the MUI Datagrid. Any suggestions?

I'm currently developing a react application and utilizing the MUI Datagrid to present some data. I have incorporated a rendercell to insert an edit icon which should trigger a pop-up modal when clicked. Below is the column setup. export const specifi ...