Skip to content
the poor coder

ReactComponent as Icon

Poor Man
Published
Reading time
1 min read
On this page

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.

JavaScript

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.

JavaScript

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.

CSS

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC