How to Use SVG in React
SVG (Scalable Vector Graphics) is a powerful technology for creating high-quality vector images. React, a popular JavaScript library for building user interfaces, also provides support for rendering SVG components. In this post, we will discuss how to use SVG in React and explore some practical examples.
Initializing a React Project
Before we start using SVG in React, let’s set up a new React project using popular tools like Create React App. Open your terminal and run the following command:
bash
npx create-react-app svg-react-app
cd svg-react-app
npm start
This will create a new React project and start the development server.
Importing SVG Files
To use SVG files in React, we need to import them as components. For example, if we have an SVG file named logo.svg
, we can import and use it in our React component as follows:
“`jsx
import { ReactComponent as Logo } from ‘./logo.svg’;
function App() {
return (
);
}
export default App;
“`
Here, the ReactComponent
is a special variable that contains the imported SVG component. We can use this component just like any other React component.
Inline SVG
Apart from using separate SVG files, we can also use inline SVG directly in our React components. This is useful when we want to create dynamic SVGs by manipulating their properties using React state or props.
“`jsx
function Circle({ radius }) {
return (
);
}
function App() {
return (
);
}
export default App;
“`
In this example, we created an Circle
component that accepts a radius
prop to determine the size of the circle. We can pass different values for the radius
prop to dynamically change the size of the circle.
Manipulating SVG with CSS
SVG elements can be easily styled using CSS. React allows us to add CSS classes to SVG components, which gives us complete control over their appearance.
“`jsx
import ‘./App.css’;
function App() {
return (
);
}
export default App;
“`
In this example, we added a CSS class custom-shape
to a rect
element. We can define the styles for this class in the App.css
file and apply any desired visual changes to the SVG element.
Conclusion
In this post, we learned how to use SVG in React. We explored importing SVG files as components, using inline SVG, and manipulating SVG elements with CSS. SVG provides a powerful and flexible way to create vector images in React, allowing us to build visually appealing and interactive applications.