ReactComponent as Icon

ReactComponent as Icon

When working with React, we often need to display icons on our web pages. To achieve this, we can use the ReactComponent as Icon approach.

Step 1:

Create a new React component for the icon, let's call it Icon.js. In this component, we will define the SVG icon.


import React from 'react';

const Icon = () => {
  return (
    <svg width="24" height="24" viewBox="0 0 24 24">
      <path fill="#000000" d="M19 3H5C3.9 3 3 3.9 3 5v14c0 1.1 0.9 2 2 2h14c1.1 0 2-0.9 2-2V5c0-1.1-0.9-2-2-2zM7 17l-2-4h14l-4-8h-4l2 4h-6.5l-2-4h-4.5l4 8z"></path>
    </svg>
  );
};

export default Icon;

In this example, we have created a simple SVG icon for a delete button.

Step 2:

Import the Icon component into your main component where you want to use the icon.


import React from 'react';
import Icon from './Icon';

const App = () => {
  return (
    <div>
      <h1>My App</h1>
      <Icon />
    </div>
  );
};

export default App;

In this example, we have imported the Icon component and used it in the App component.

Step 3:

Style the icon as per your requirements. You can use CSS to style the SVG icon.


svg {
  fill: red;
  width: 24px;
  height: 24px;
}

In this example, we have applied the fill, width, and height properties to the SVG icon to change its color and size.

This is just one way to use the ReactComponent as Icon approach. There are other ways to achieve the same result, but this is a simple and effective method.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe