Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  74] [ 6]  / answers: 1 / hits: 37277  / 5 Years ago, fri, october 18, 2019, 12:00:00

Attempts to add an icon to option in react-select. I imported svg icons from the files england.svg, germany.svg. I created customSingleValue and put it in


<Select components={{ SingleValue: customSingleValue }} />

Labels are displayed, but the icons are not.


Demo here: https://stackblitz.com/edit/react-q19sor


import Select from 'react-select'
import { ReactComponent as IconFlagEngland } from "./england.svg";
import { ReactComponent as IconFlagGermany } from "./germany.svg";

const options = [
{ value: 'England', label: 'England', icon: <IconFlagEngland/> },
{ value: 'Germany', label: 'Germany', icon: <IconFlagGermany/> }
]

const customSingleValue = ({ options }) => (
<div className="input-select">
<div className="input-select__single-value">
{ options.icon && <span className="input-select__icon">{ options.icon }</span> }
<span>{ options.label }</span>
</div>
</div>
);

class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}

render() {
return (
<Select
defaultValue={ options [0] }
options={ options }
/*styles={ selectCustomStyles }*/
/*onChange={ changeSelectHandler }*/
components={ {SingleValue: customSingleValue } }
/>
);
}
}

render(<App />, document.getElementById('root'));

More From » css

 Answers
3

I have found a workaround to solve the issue. My technique is similar to that of @canda.


import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";
import Select, { components } from "react-select";

const options = [
{ value: "England", label: "England", icon: "england.svg" },
{ value: "Germany", label: "Germany", icon: "germany.svg" }
];

const { Option } = components;
const IconOption = props => (
<Option {...props}>
<img
src={require('./' + props.data.icon)}
style={{ width: 36 }}
alt={props.data.label}
/>
{props.data.label}
</Option>
);

class App extends Component {
constructor() {
super();
this.state = {
name: "React"
};
}

render() {
return (
<Select
defaultValue={options[0]}
options={options}
components={{ Option: IconOption }}
/>
);
}
}

render(<App />, document.getElementById("root"));

[#51560] Wednesday, October 9, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yvettel

Total Points: 517
Total Questions: 101
Total Answers: 102

Location: Vanuatu
Member since Wed, Oct 14, 2020
4 Years ago
;