0

If we have to insert normal html elements with React Variables in JSX, it is easy, We can use dangerouslySetInnerHTML, or we can use any npm packahe html-react-parser.

Below code works fine.

const thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>
    );
}

But If we try to add any Link element inside the html, It do not convert into anchor tag.

const thisIsMyCopy = '<Link to="/button" >button</Link>';

If we inspect this element, this does not shows as anchor tag, Below is the Sandbox example for this.

https://codesandbox.io/embed/react-example-y5m94?fontsize=14&hidenavigation=1&theme=dark I hope, many of you react developer must have

Nimish goel
  • 2,561
  • 6
  • 27
  • 42

2 Answers2

0

Please try to make it not string:

const thisIsNotWorking = <Link to="/button" >button</Link>;
0
const thisIsMyCopy = '<Link to="/button" >button</Link>';

Here this "thisIsMyCopy" is not a regular HTML element because of which when you try to insert a non HTML element or something random into the DOM, the DOM does not understand this element.check Document Type Definition (DTD), The DTD specifies which element types are possible (i.e. it defines the set of element types) and also the valid combinations in which they may appear in a document If you'll replace it by

const thisIsMyCopy = '<a to="/button" >button</a>';

It will work because is a valid HTML element.

2)From your statement it looks like, thisIsMyCopy is actually a React Router Link component. so in order to render a custom Component you can always render it as a child. The purpose of dangerouslySetInnerHTML is to set some valid HTML.