DEV Community

loading...
Cover image for React Without JSX

React Without JSX

mrwolferinc profile image mrwolferinc ・2 min read

JSX is not a requirement for React. Using React without JSX is especially convenient when you don't want to set up compilation in your build environment.

This tutorial will show you how to use React without JSX. It will also show you how code written in JSX is converted to plain JavaScript.


What is JSX?

Consider the following variable decleration:

const element = <h1>Hello, world!</h1>;
Enter fullscreen mode Exit fullscreen mode

This strange tag syntax is neither a string nor HTML.

It is called JSX, and it is a syntax extension to JavaScript. It is commonly used with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.


Converting to JavaScript

Each JSX element is actually syntactic sugar for calling the React.createElement() method. This means that any code that is written in JSX can also be written in plain JavaScript.

For example, this code is written in JSX:

class Hello extends React.Component {
  render() {
    return <h1>Hello, {this.props.toWhat}!</h1>;
  }
}

ReactDOM.render(
  <Hello toWhat="world" />,
  document.getElementById("root")
);
Enter fullscreen mode Exit fullscreen mode

It can be compiled to this code that doesn't use JSX:

class Hello extends React.Component {
  render() {
    return React.createElement("h1", null, `Hello, ${this.props.toWhat}!`);
  }
}

ReactDOM.render(
  React.createElement(Hello, { toWhat: "world" }, null),
  document.getElementById("root")
);
Enter fullscreen mode Exit fullscreen mode

This happens because the JSX code is converted to JavaScript using the package Babel during compilation. If you're curious to see more examples of how this works, you can try out Babel's online compiler.


Shorthands

If you get tired of typing React.createElement so much, one common pattern is to assign a shorthand:

const e = React.createElement;

ReactDOM.render(
  e("h1", null, "Hello, world!"),
  document.getElementById("root")
);
Enter fullscreen mode Exit fullscreen mode

If you use this shorthand form for React.createElement, it can be almost as convenient to use React without JSX.

Discussion (0)

Forem Open with the Forem app