2

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

4
  • show your state pls Commented Aug 5, 2018 at 10:56
  • You probably need to look into whatever you're using to transpile your js. For example if you're using webpack you may need to setup a loader to handle svg and make it part of your built app. Commented Aug 5, 2018 at 10:58
  • thanks for you replay, this is constructor : constructor() { super(); this.state = { SvgMap :"" } } Commented Aug 5, 2018 at 11:00
  • why not using <img src="../svg/floor1.svg" /> ? Commented Aug 5, 2018 at 11:06

2 Answers 2

1

Try using like this:

<span dangerouslySetInnerHTML={{ __html: `<img src=${this.state.SvgMap} />` }} />
Sign up to request clarification or add additional context in comments.

Comments

0

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>
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.