Currently I have this in one of my components:
{someObject.map(obj => (
<div
dangerouslySetInnerHTML={{
__html: obj.text
}}
/>
))}
Basically, I am mapping over someObject
which on another file. The structure is like this:
export default someObject = [
{
obj: "<p>Some text 1.</p>"
},
{
obj: "<p>Some text 2.</p>"
}
]
I'm just simplifying the content for demonstration's sake. However, I ran into a problem because I need to use the <Link />
component in one of the items. As in:
export default someObject = [
{
obj: "<p>Some text 1.</p>"
},
{
obj: "<p>Some text 2.</p>"
},
{
obj: "<p>Some text 2 and <Link to="/someroute">link</Link>.</p>"
}
]
However, it's not working because that entire <p></p>
tag is wrapped in dangerouslySetInnerHTML
.
I can just use plain <a></a>
tag for the link but that doesn't seem like a good solution as the entire application would reload instead of just going to another route.
What are the other options to make this work?
dangerouslySetInnerHTML is a property that you can use on HTML elements in a React application to programmatically set their content. Instead of using a selector to grab the HTML element, then setting its innerHTML , you can use this property directly on the element.
Is it OK to use dangerouslySetInnerHTML? Yes, it will help you render markups in ways that the React JSX element will prohibit by default. It will help you pass HTML directly into a component within JSX.
In general, setting HTML from code is risky because it may expose your users to a cross-site scripting (XSS) attack. You can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it's dangerous.
React dangerouslySetInnerHTML is an HTML property that makes it easy to programmatically set the HTML elements from an external source. It has replaced the innerHTML used in the browser DOM. dangerouslySetInnerHTML helps React know how to handle the HTML elements in a component where the contents are to be rendered.
Why don't you just export the object as a jsx object? I think use dangerouslySetInnerHTML
is a bad practice, it might cause XSS attack.
const someObject = [
{
obj: <p>Some text 1.</p>
},
{
obj: <p>Some text 2.<a href="https://google.com">google</a></p>
}
]
class App extends React.Component {
render(){
return (
<div className="App">
<h1>Hello world</h1>
<h2>Jsx object goes here {someObject[1].obj}</h2>
</div>
)};
}
const rootElement = document.getElementById("container");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With