0

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

Haseeb Saeed
  • 599
  • 2
  • 4
  • 19
  • I found this answer and it works well for me: https://stackoverflow.com/questions/44900569/turning-an-svg-string-into-an-image-in-a-react-component – Haseeb Saeed Jan 05 '22 at 18:56

2 Answers2

1

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

Janik
  • 688
  • 1
  • 6
  • 12
1

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

<img key={j} src={Data.image_data} />