Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 10, 2020 09:37 pm GMT

How to use SVGs in your React App

Trying to render an SVG in your React app, and getting errors? Youre not alone - its a relatively common issue.

There are two ways to do it, and both have tradeoffs.

Using <img> tags, and passing your SVGs URL

Heres a basic example:

import React from 'react';import logoSrc from './logo.svg';const MyLogo = () => {  return <img src={logoSrc} />;};

The benefit of this approach is that your logo will not end up in your bundle, but rather exported as a static file when you run yarn build (assuming youre using a standard webpack config, such as the one found in create-react-app).

This then gives you the option of aggressively caching icons that you know wont change.

You would typically use this approach for larger company logos on your marketing site, or for illustrations in your app.

Creating a React component, and passing props

The other option is to create a React component containing your SVG. Also known as inlining your SVG.

This done by pasting your raw svg markup into a new React component.

There are a few ways to achieve this:

  • Manually, byremoving/replacing all HTML props with the React equivalent, and adding {...props} to the main svg element),
  • CLI via SVGR - a utility to automate this process
  • Webpack config via SVGR

If youre using create-react-app, it already has SVGRs webpack config built-in, so you can already use your SVGs like React components:

import Star from './star.svg';const App = () => (  <div>    <Star />  </div>);

Heres what a manually created SVG-based React component looks like:

import React from 'react';export const DeleteIcon = (props) => (  <svg    xmlns="http://www.w3.org/2000/svg"    height="24px"    viewBox="0 0 24 24"    {...props}  >    <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" />    <path d="M0 0h24v24H0z" fill="none" />  </svg>);

This approach lets you easily access props on your SVG icon. For example, changing the fill color:

<DeleteIcon fill="#fff" />

The downside being that your icons wont be as easily cached, so I would use this approach for smaller icons, such as the Material Design Icons.

(This is an article posted to my blog at maxrozen.com. You can read it online by clicking here.)


Original Link: https://dev.to/rozenmd/how-to-use-svgs-in-your-react-app-2c0j

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To