Why use JSX when you can use template literals?

Yesterday, I wrote about my favourite ES6 features. Template literals take the top spot. I think they make JSX, the JavaScript syntax extension React uses, largely pointless.

Let’s look at some simple examples from the React documentation. You’ll have to forgive the syntax highlighting in the JSX snippets; I refuse to add more CSS just to highlight a redundant pseudo-language.

Inserting a variable

JSX

const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;

Template literal

const name = 'Josh Perez';
const element = `<h1>Hello, ${name}</h1>`;

Inserting a function call

JSX

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);

Template literal

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

const element = `
  <h1>
    Hello, ${formatName(user)}!
  </h1>
`;

Do you see my point?

I literally cannot see how JSX is any better than template literals.


If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!