Using SVG (Scalable Vector Graphics) in React is quite straightforward. React treats SVG just like any other HTML element, so you can include SVG tags directly in your JSX code. Here’s a step-by-step guide on how to use SVG in React:
- Create a React project: If you don’t have a React project set up already, you can create one using Create React App or any other preferred method.
- Import SVG files: You can use SVG files directly in React components by importing them. First, place your SVG files in a directory (e.g., src/assets/svg), and then import the SVG file at the beginning of your component file like this:
import React from 'react';
import { ReactComponent as MySVGIcon } from '../assets/svg/my-svg-icon.svg';
The ReactComponent import alias is used for SVG files so that React treats it as a component.
Use SVG in JSX
Now that you have imported the SVG, you can use it in your JSX code as if it were a regular React component:
function MyComponent() {
return (
<div>
<h1>Hello, SVG in React!</h1>
<MySVGIcon width="100" height="100" />
</div>
);
}
In this example, we have used the imported SVG component (MySVGIcon) just like any other React component. You can adjust the width and height attributes to control the size of the SVG as needed.
Inline SVG
If you have a small SVG or prefer to include it directly in your JSX code, you can do so by using a multiline string or template literal:
function MyComponent() {
return (
<div>
<h1>Hello, Inline SVG in React!</h1>
<svg
width="100"
height="100"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100"
>
<circle cx="50" cy="50" r="40" fill="blue" />
</svg>
</div>
);
}
In this example, we have directly included an inline SVG using the <svg> element. Remember to include the required SVG attributes like xmlns and viewBox for proper rendering.
You can now use SVG files or inline SVG directly in your React components. SVGs are great for creating scalable and resolution-independent graphics and icons in web applications.