React Without JSX

React Without JSX


Nov 28 2024

React is widely known for JSX. But did you know you can use React without JSX? Let’s explore how it works and why you might want to consider it.

What is JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript files. It is commonly used with React to describe what the user interface (UI) should look like as shown below:

const App = () => {
  return <h1>Hello, World!</h1>;
};

However, behind the scenes, JSX gets compiled into plain JavaScript using the React.createElement method. This means JSX is not required to write React applications.

React Without JSX

To use React without JSX, you need to manually write the equivalent the React.createElement() method calls.

This method takes three arguments:

  • the type of the element (e.g., a string representing an HTML - tag or a custom component),
  • optional attributes (or props),
  • children elements.

Here is the same example as above, but without JSX:

const App = () => {
  return React.createElement('h1', null, 'Hello, World!');
};

Creating Nested Elements

Components are mostly nested, if you want to add children to an specific element, you can pass additional react.createElement method calls as shown below:

const element = React.createElement('div', null,
  React.createElement('h1', null, 'Hello, world!'),
  React.createElement('p', null, 'This is a paragraph.')
);

Here is the corresponding HTML structure:

<div>
  <h1>Hello, world!</h1>
  <p>This is a paragraph</p>
</div>

Adding Props To Elements

You can also add props to your elements by passing an object as the second argument to the createElement method.

For example, to add a class name to an element, you can write like this:

const element = React.createElement('div', { className: 'container' },
  React.createElement('h1', null, 'Hello, world!'),
  React.createElement('p', null, 'This is a paragraph.')
);

This code creates a div element with two child elements and pass a classname props to it.

<div className="container">
  <h1>Hello, world!</h1>
  <p>This is a paragraph</p>
</div>

Conclusion

While React with JSX is the standard and recommended way of writing React components, it’s essential to understand that JSX is just a convenient syntax extension and not a requirement for using React.

Thank you for reading.