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:-
- 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])
- 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.
In the below section of the code it should render as html element instead of string.
