Search code examples
reactjsimagerequirereact-select

Use image as icon with react-select


I would like to add an image as Icon with react-select. I did all right but I have a problem with the fact that, in react, images are written like this :

<img src={require(...)} />

So I use react-select like this :

const IconOption = (props) => (

  <Option {... props}>
    <div>
      <img src={require(props.data.image)} />
    </div>
  </Option>
);

And then call for the select box :

render() {
    return (
      <Select
        classNamePrefix="react-select"
        placeholder={"Search..."}
        onChange={this.handleChange}
        components={{ DropdownIndicator: () => null, Option: IconOption }}
        options={this.state.options}
        openMenuOnClick={false}
        styles={customStyle}
      />
    );
  }

I tried to write :

const IconOption = (props) => (

  <Option {... props}>
    <div>
      {props.data.image}
    </div>
  </Option>
);

Which gives me :

./css/img/PROFILEPICTURE.jpg

It is exactly what I want to get, the path is correct. If I exactly write :

const IconOption = (props) => (

  <Option {... props}>
    <div>
      <img src="./css/img/PROFILEPICTURE.jpg" />
    </div>
  </Option>
);

Image is correctly displayed.

If I write the first code, which is the one to get different picture for each item in selectbox, I got an error :

enter image description here

Any solution to not use require function for img in react?

Edit :

I also tried :

const IconOption = (props) => 
  (
    <Option {... props}>
      <div>
        <img src={props.data.image} />
        {props.data.label}
      </div>
    </Option>
  );

And i got not found images :

enter image description here


Solution

  • You just have to remove the require since your image is not part of the compiled react app:

    const IconOption = (props) => (
      <Option {... props}>
        <div>
          <img src={props.data.image} />
        </div>
      </Option>
    );