1. Using the img tag
One simple way to display SVG icons in a React component is by using the img tag. You can import the SVG file as a module and set it as the source of the img tag. Here’s an example:
{`import React from 'react';
import icon from './icon.svg';
const IconComponent = () => {
return ;
};
export default IconComponent;`}
In this example, we import the SVG file as a module and assign it to the icon
variable. Then, we use the src
attribute of the img tag to set the source of the image to the icon
variable.
2. Using the object tag
Another way to display SVG icons in a React component is by using the object tag. The object tag allows you to embed external content, such as SVG files, into your web page. Here’s an example:
{`import React from 'react';
import icon from './icon.svg';
const IconComponent = () => {
return ;
};
export default IconComponent;`}
In this example, we set the type
attribute of the object tag to image/svg+xml
to specify that we are embedding an SVG file. Then, we use the data
attribute to set the source of the SVG file.
3. Using the SVG file directly
If you prefer to include the SVG code directly in your React component, you can do so by importing the SVG file as a string and using it in your component’s JSX. Here’s an example:
{`import React from 'react';
import { ReactComponent as Icon } from './icon.svg';
const IconComponent = () => {
return ;
};
export default IconComponent;`}
In this example, we use the ReactComponent
import syntax to import the SVG file as a React component. We then use this component in our JSX to render the SVG icon.
Conclusion
Displaying SVG icons in a React component can be achieved using different approaches. Whether you choose to use the img tag, object tag, or import the SVG file directly, React provides flexibility in incorporating SVG icons into your UI. Choose the approach that best suits your project requirements and start adding beautiful and scalable icons to your React applications.
Leave a Reply