React Without JSX
By gobrain
Jul 9th, 2024
JSX is a special syntax extension for JavaScript that lets you write HTML-like code directly within your JavaScript files. It is primarily used with React to build user interfaces. But did you know you can also build interfaces in React without using JSX? Let's see how to achieve this.
React Without JSX
To create a React component without using JSX, you can use the React.createElement method.
The react.createElement method takes three arguments:
- the type of the element,
- its optional attributes (or props),
- its children
Let’s see an example:
import React from 'react';
const MyComponent = () => {
return React.createElement(
'div',
{ className: 'container' },
React.createElement('h1', {className:'title'}, 'Hello, React without JSX!'),
React.createElement('p', null, 'This is how you can use React without JSX.')
);
};
export default MyComponent;
And, here is the corresponding JSX structure of it:
<div className="container">
<h1 className="title">Hello, React without JSX!</h1>
<p>This is how you can use React without JSX.</p>
</div>
An Important Note
The React official documentation states that React.createElement is now considered a legacy API in React 18. They recommend using JSX.
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.