Home > Back-end >  How to render an SVG on the DOM in react 18?
How to render an SVG on the DOM in react 18?

Time:10-20

I have seen so many people discussing stuff that doesn't work all the times.

I am using react 18. I want to import an SVG file on my disk and render it on my DOM.

I tried to import it as:

import { ReactComponent as Underconstruction } from '../../media/business/under-construction.svg';

const Sidebar= ()=> {
  return <Underconstruction />
}

But it showed me this error:

enter image description here

I have also tried to use it as a regular image tag and it showed me the same error:

const Sidebar= ()=> {
  return <img src={require('../../media/business/under-construction.svg')} />
}

and I have tried to use require() but it showed 404 couldn't find the file:

const Sidebar= ()=> {
  return <img src="../../media/business/under-construction.svg" />
}

I am using create-react-app

I am using react 18.

20 Oct 2022.

CodePudding user response:

The easiest way is putting your svg in public folder like this

easiest

Then you can use it directly using path, without import as component:

<img src="/media/bussiness/under-construction.svg" />

Hope it help!

CodePudding user response:

The easiest way to use your svg as a React component. So you do not need to care about the config

import React from 'react'

export function YourFileName() {
  return (
    <svg
     ...
    >
      <path
        ...
        ...
      />
    </svg>
  )
}

You can get svg tag by open svg by your code editor like vscode

CodePudding user response:

Here are a couple of options for importing SVG into React:

  • Importing SVG in react as an image tag
  • Import SVG in react as JSX
  • Importing SVG as react component (Inline SVGs)

Importing SVGs in React Image Tag

import myLogo from '/path/to/image.svg'
 
const Button = () => {
  return (
    <button>
      <img src={myLogo} alt="SVG logo image"/>
    </button>
  );
}

Importing SVG in React as JSX

<svg 
  xmlns="http://www.w3.org/2000/svg"
  
  fill="none"
  viewBox="0 0 24 24"
  stroke="currentColor"
  stroke-width="2"
>
  <path 
  stroke-linecap="round"
  stroke-linejoin="round"
  d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
  />
</svg>

Importing SVGs as React Component

export const LeftArrow = () =>{
  return(
    <svg 
    xmlns="http://www.w3.org/2000/svg"
    className="h-6 w-6"
    fill="none"
    viewBox="0 0 24 24"
    stroke="currentColor"
    strokeWidth={2}
  >
    <path 
    strokeLinecap="round"
    strokeLinejoin="round"
    d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
  />
  </svg>
  )
}

Now, you can import and render the react SVG component in another component like this:

import { LeftArrow } from './path/to/LeftArrow.jsx'
 
export const Button = () =>{
  return(
    <button>
      <LeftArrow />
    </button>
  )
}
  • Related