Home > Back-end >  Displaying raw SVG in React
Displaying raw SVG in React

Time:01-06

Hi there I'm getting an SVG from an api in this form:

<svg> ..... </svg>

I'm passing this svg as an props to this MainDisplay Component

class MainDispay extends React.Component {
  constructor(props) {
    donothing(props);
    super(props);
    console.log("props", this.props.Collections);
  }

  async componentDidMount() {}

  render() {
    return (
      <>
        {this.props.Collections.map((DataObj, i) => (
          <div key={i}>
            <div>{DataObj.name}</div>
            {this.props.Collections[i].DisplayProps.map((Data, j) => (
              <div key={j}>{Data.image_data}</div>
            ))}
          </div>
        ))}
      </>
    );
  }
}

Only problem is that the Data.image_data displays <svg>.....<svg> instead of an image.

Any idea how to display image instead. THANKS in ADVANCE

CodePudding user response:

You can use Reacts dangerouslySetInnerHTML to render any supplied html string:

<div key={j} dangerouslySetInnerHTML={{__html: Data.image_data}} />

Be careful! This attribute opens your app for vulnerable cross-site scripting attacks. Make sure to sanitize your image_data to strip any html other than svg. More on this e.g. in this answer: https://stackoverflow.com/a/1637573/9969672

CodePudding user response:

One effective way is to pass SVG as a source of 'img' tag.

<img key={j} src={Data.image_data} />
  •  Tags:  
  • Related