Kamal Benbrahim
Kamal Benbrahim

Reputation: 29

Cannot import SVG dynamic using React

I tried the below code to import SVG dynamically.

let selectedFloor = require('../svg/floor1.svg');
this.setState({
  SvgMap : selectedFloor
})

render() {
  return (
    <div>
      <span dangerouslySetInnerHTML={{ __html: this.state.SvgMap }} />
    </div>
  );

Result:

Result

Upvotes: 2

Views: 2732

Answers (2)

Aliaksandr Pitkevich
Aliaksandr Pitkevich

Reputation: 834

Try using like this:

<span dangerouslySetInnerHTML={{ __html: `<img src=${this.state.SvgMap} />` }} />

Upvotes: 1

naortor
naortor

Reputation: 2089

I think you should use the img tag, and you can keep the path to the SVG file in the state, or only the name.

const selectedFloor = 'floor1.svg';
this.setState({
    SvgMap : selectedFloor
});

render() {   
    return (
      <div>
          <img src={`../svg/${this.state.SvgMap}`}
      </div>
    );
}

Upvotes: 0

Related Questions