Convert template literal to string

Viewed 634

I have a React component in which it receives a prop codeBlock, it is then stored in the state of the component.

which has following structure:

codeBlock = {
  code: `<div></div>`,
  language: 'html'
}

I want to convert this codeBlock.code which is a template literal string into a html element, so that when I add/append this while rendering the element I will get the DOM element not the literal string.

Things I've tried so far,

In the componentDidMount(), I tried two different ways:-

  1. Using DOMParser:
componentDidMount() {
  const parser = new DOMParser();
  const output = parser.parseFromString(this.state.codeBlock.code, 'text/html');
  this.setState({
    output
  });
}

This method doesn't work and throws this error: objects are not valid as a react child (found: [object htmldocument])

  1. Using String.raw:
componentDidMount() {
  this.setState({
    output: String.raw `${this.state.codeBlock.code}`
  });
}

This method prints the template string as it is and doesn't create any element.

Screenshot: enter image description here

In the below section of the code it should render as html element instead of string.

2 Answers

You can use innerHTML.

HTML:

<div id="elem"></div>

JS:

const codeBlock = {
  code: `<div class="container"></div>`,
  language: 'html'
}

const elem = document.getElementById("elem");
elem.innerHTML = codeBlock.code;

The best solution would be not to pass a string but a React element (or both):

codeBlock = {
  code: "<div></div>", // string here
  rendered: <div></div>, // jsx here
  language: 'html'
}

This you can easily render into a React component. However, if you really have to deal with a string of html (as the name codeBlock, and the availability of other languages would suggest), you would have to use innerHTML or React's equivalent dangerouslySetInnerHTML.

Notice that it doesn't matter (or help) that the string value was originally created using template literal syntax. It makes no difference to the component that is receiving the string.

Related