I am getting a JSON response that has an image property for each key. This image property is the entire image element tag with properties. I am trying to pass that down into a child component, but upon attempting to render, it just shows up as plain html text on the page. Is there a way to render it as an actual image tag? I have attached a screenshot of the JSON response
` <div className="aspect-[3/2] md:aspect-square overflow-hidden">
{props.image}
</div>
<span className="block py-5">{props.name}</span>`
CodePudding user response:
You could use dangerouslySetInnerHTML
but you'll have to wrap it in a span or div or something:
// Example class component
class Thingy extends React.Component {
render() {
const {source} = this.props;
console.log("rendered");
return (
<span dangerouslySetInnerHTML={{ __html: source }} />
);
}
}
// Render it
ReactDOM.render(
<Thingy source={`<img src="https://images.unsplash.com/photo-1490730141103-6cac27aaab94?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1000&q=80" />`} />,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>