Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weird html rendering issue with react

I'm trying to render the message with html tags inside it. The rendering is working fine if the string is passed as prop, but when the same is passed from a variable the display text has encoded text.

Any idea how do I get it working in both scenarios.?

class Hello extends React.Component {
  render() {
    console.log(this.props.name)
    return <div>{this.props.name}</div>;
  }
}

ReactDOM.render(
  <Hello name="&lt;p&gt;How are you?&lt;/p&gt;" />,
  document.getElementById('container') --> **<p>How are you?</p>** 
);


class HelloOther extends React.Component {
  render() {
    const name = "&lt;p&gt;How are you?&lt;/p&gt;" 
    return <Hello name={name} />;
  }
}

ReactDOM.render(
  <HelloOther />,
  document.getElementById('container2') -- &lt;p&gt;How are you?&lt;/p&gt; -- > why?
);

Fiddle link - https://jsfiddle.net/d6s7be1f/2/

like image 265
StateLess Avatar asked Apr 10 '26 21:04

StateLess


1 Answers

class Hello extends React.Component {
  createMarkup() {
    return {__html: this.props.name};
  }
  render() {
    return <div dangerouslySetInnerHTML={this.createMarkup()} />;
  }
}
like image 146
Vagan M. Avatar answered Apr 12 '26 09:04

Vagan M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!