How to add icon in select option in react js?
July 03, 2024Hi Friends π,
Welcome To aHoisting!
To add icon in select option in react js, you can use {option.icon}
. It will add icon in select option in react js.
Today, I am going to show you, how to add icon in select option in react js.
Table of contents
- Install and create a new React app.
- Import react component.
- Create a Component.
Letβs start with the first step.
Step 1: Install and create a new React app.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import react component.
After installing, you have to import your React component. To do this, add the following line to the top of your component file.
import React, { useState } from 'react';
import './App.css'; // Import your custom styles
Step 3: Create a Component.
You can use className="select-options"
to add icon in select option in react js.
<div className="select-options">
{options.map(option => (
<div
key={option.value}
className="select-option"
onClick={() => setSelected(option)}
>
<span className="icon">{option.icon}</span>
<span>{option.label}</span>
</div>
))}
</div>
Add icon in select option example.
The below code is an example of a React. You have to import ./App.css
and set {option.icon}
to add icon in select option in react js.
App.js
import React, { useState } from 'react';
import './App.css'; // Import your custom styles
const options = [
{ value: 'apple', label: 'Apple', icon: 'π' },
{ value: 'banana', label: 'Banana', icon: 'π' },
{ value: 'cherry', label: 'Cherry', icon: 'π' },
];
const SelectOption = () => {
const [selected, setSelected] = useState(options[0]);
return (
<div className="custom-select">
<div className="select-header">
<span className="icon">{selected.icon}</span>
<span>{selected.label}</span>
<span className="arrow">βΌ</span>
</div>
<div className="select-options">
{options.map(option => (
<div
key={option.value}
className="select-option"
onClick={() => setSelected(option)}
>
<span className="icon">{option.icon}</span>
<span>{option.label}</span>
</div>
))}
</div>
</div>
);
};
export default SelectOption;
App.css
.custom-select {
position: relative;
width: 200px;
}
.select-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
border: 1px solid #ccc;
cursor: pointer;
}
.select-options {
display: none;
position: absolute;
top: 100%;
left: 0;
width: 100%;
border: 1px solid #ccc;
background-color: #fff;
}
.custom-select:hover .select-options {
display: block;
}
.select-option {
padding: 10px;
display: flex;
align-items: center;
cursor: pointer;
}
.select-option:hover {
background-color: #f0f0f0;
}
.icon {
margin-right: 10px;
}
In the above code example, I have used the {option.icon}
and add icon in select option in react js.
Check the output of the above code.
All the best π