score:1

Accepted answer

fyi, template literals are string literals.
https://developer.mozilla.org/en-us/docs/web/javascript/reference/template_literals

you can just remove the template literal :)

var article = {
  title: 'hello world',
 }

const app = () => {
  var {title} = article
  var html = <header>
    <h1>{title}</h1>
  </header>
  return <div>{html}</div>;
}

score:0

you can do so with react's dangerouslysetinnerhtml but as you can tell from the name, it is dangerous because it’s easy to inadvertently expose your users to a cross-site scripting (xss) attack.

you can still use it if you understand the risk:

import react from 'react';

var article = {
  title: "hello world"
};

const app = () => {
  var { title } = article;
  return (
    <div
      dangerouslysetinnerhtml={{
        __html: `<header><h1>${title}</h1></header>`
      }}
    />
  );
};

if you are just trying to embed expressions in jsx, simply wrap them in curly braces:

import react from "react";

var article = {
  title: "hello world"
};

const app = () => {
  var { title } = article;
  return (
    <div>
      <header>
        <h1>{title}</h1>
      </header>
    </div>
  );
};

score:0

in your case, the variable html is just a string, and when you try to render it inside the jsx like <div>{html}</div> it is explicitly being rendered as a string rather than html.

it is nothing different than trying to render <div>{"<header>hello there</header>"}</div>. while saving to the result that you want to a variable works, i wouldn't recommend it. for your use-case it is much simpler to just use jsx directly instead. for example,

var article = {
  title: "hello world"
};

const app = () => {
  var { title } = article;
  return (
    <div>
      <header>
        <h1>{title}</h1>
      </header>
    </div>
  );
};

if you have a lot of elements that you were trying to render, abstracting the logic to a new component is always a better idea. for example,

// new header component
const header = (props) => {
  return (
    <header>
       <h1>{props.title}</h1>
      {/* other-components or elements you want to render */}
    </header>
  );
}


var article = {
  title: "hello world"
};

const app = () => {
  var { title } = article;
  return (
    <div>
      <header title={title}/>
    </div>
  );
};

Related Query

More Query from same tag