How to Render a String with Jsx in React

How to render jsx stored as a string in ReactJS

Hi I figured out JsxParser is the right way of solving my problem.
react-jsx-parser provides capability to parser and render react component from JSX string.

How to render HTML string as real HTML?

Check if the text you're trying to append to the node is not escaped like this:

var prop = {
match: {
description: '<h1>Hi there!</h1>'
}
};

Instead of this:

var prop = {
match: {
description: '<h1>Hi there!</h1>'
}
};

if is escaped you should convert it from your server-side.

The node is text because is escaped

The node is text because is escaped

The node is a dom node because isn't escaped

The node is a dom node because isn't escaped

Render string as JSX in React.js

I am assuming your original issue is that the value is rendered as string instead of an element in React

You can use the JSX attribute dangerouslySetInnerHTML

Example :

render() {
str = '<img class="emojione" alt=" title=":flag_gb:" src="https://cdn.jsdelivr.net/emojione/assets/4.0/png/32/1f1ec-1f1e7.png"/>'
return( <div dangerouslySetInnerHTML={{__html: str}}></div> )
}

Original SO Answer refer - [ How do I convert a string to jsx? ]

How can I render a string in React JS which has components?

You can use dangerouslySetInnerHTML attribute on an html element to set the string as HTML. But know that setting HTML like this in React is risky as this may expose your users to a cross-site scripting (XSS) attack.
To know more on how to use it, refer here on official React docs:
https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

Posting an example use-case below on how to use it.

function App() {

function getMarkup() {
return {__html: '<h3>My Content here..</h3>'}; // The HTML string you want to set
}

return (
<div className="App">
<div dangerouslySetInnerHTML={getMarkup()}></div>
</div>
);
}

Render string containing JSX in react binding

Unfortunately, template literals won't work with React components.

However, you could utilize React.Fragment to accomplish what you need, like in the following example:

function TooltipContent(props) {
const { variant = "default" } = props;
const FAQLink = () => <a href="https://google.com">I am a link!</a>;

let content;

switch (variant) {
case "risk":
content = (
<React.Fragment>
RISK! <br />
<FAQLink />
</React.Fragment>
);
break;
case "no-risk":
content = "NO RISK";
break;
default:
content = variant;
}
return <p>{content}</p>;
}

Here's a working example:

  • CodeSandbox

ReactJS convert HTML string to JSX

By default, React escapes the HTML to prevent XSS (Cross-site scripting). If you really want to render HTML, you can use the dangerouslySetInnerHTML property:

<td dangerouslySetInnerHTML={{__html: this.state.actions}} />

React forces this intentionally-cumbersome syntax so that you don't accidentally render text as HTML and introduce XSS bugs.



Related Topics



Leave a reply



Submit