Ichrak Mansour
Ichrak Mansour

Reputation: 1932

How dispaly an svg on the option of select with ReactJs?

I have a select flags which the options are the img (which src are svg)

My codeSandbox.


Config.default = "fr";
Config.list = {
  de: {
    text: "Deutsch",
    icon: require("./images/de.svg")
  },
  en: {
    text: "English",
    icon: require("./images/eng.svg")
  },
  it: {
    text: "Italiano",
    icon: require("./images/italy.svg")
  }
};
class App extends Component {
  constructor() {
    super();

    this.state = {
      language: Config.default
    };
  }

  render() {
    return (
      <header className="d-flex align-items-end justify-content-end">
        <LanguageList Language={this.state.language} />
        <FormControl variant="outlined">
          <div className="wrap-select">
            <Select
              value={this.state.language}
              className="select-lang"
              onChange={e => this.setState({ language: e.target.value })}
              inputProps={{
                name: "locale"
              }}
            >
              <MenuItem value="en">
                <div className="wrap-content-lang">
                  <img width="20" src="./images/eng.svg" />
                </div>
              </MenuItem>
              <MenuItem value="it">
                <div className="wrap-content-lang">
                  <img width="20" src="./images/italy.svg" alt="it" />
                </div>
              </MenuItem>
              <MenuItem value="de">
                <div className="wrap-content-lang">
                  <img width="20" src="./images/de.svg" />
                </div>
              </MenuItem>
            </Select>
          </div>
        </FormControl>
      </header>
    );
  }
}

When I run it, I get:

enter image description here

The pictures are not displayed, How can I display it ?

Upvotes: 2

Views: 2009

Answers (2)

Dennis Vash
Dennis Vash

Reputation: 53894

The problem is that such src path not available in run time:

<img width="20" src="./images/eng.svg" alt="en" />

// instead
<img src={require("./images/eng.svg")}/>

In buildtime, webpack generates a hashed path, see Adding Images, Fonts, and Files and @gdh answer.

import { ReactComponent as GermanFlag } from "./images/de.svg";

class App extends Component {
  render() {
    return <GermanFlag />;
  }
}

Edit vibrant-forest-t5k7n

Upvotes: 2

gdh
gdh

Reputation: 13682

With create react app, to display svg, you can use import to display images.

import ItalySVG from './images/italy.svg'

Or - you can require it.

<img src={require("./images/italy.svg")}/>

However, You will still have issue with codesandbox to import svgs because of the open issue

If you are working in codesandbox, then for now you can use images instead. It works. See working demo

Upvotes: 2

Related Questions