Developers new to seeing React code for the first time might see JSX and think why is there HTML in my JavaScript? However, JSX is not actually HTML or a string. It is a syntax extension to JavaScript.
What does this mean? - Anything you can do with JSX you can do with plain JavaScript. Although you will use JSX in most cases, this clears up the common misconception that you must use JSX when using React.
Since we use it all the time, it is useful to see what this abstraction is actually doing under the hood.
So what happens when we create a React component that renders some JSX? It will be converted to use the React.createElement API which returns a new React element of the type it was given. A React element describes what you want to see in your user interface and is just a plain object. This type can be any tag name as a string (examples: 'div', 'h2', 'span'), a React component, or a React fragment. React.createElement also takes in props and children arguments. The React DOM takes care of updating the DOM to match React elements.
React.createElement(
type,
[props],
[...children]
)
Lets look at an example
We will create a component Cat
that takes in a name prop and renders a heading with a string telling us the cats name.
Using JSX:
import React from "react";
import ReactDOM from "react-dom";
class Cat extends React.Component {
render() {
return <h1>My name is {this.props.name}</h1>
}
}
ReactDOM.render( <Cat name="Fishguts" />,
document.getElementById("app")
);
Now lets look at how we would rewrite this without JSX using React.createElement. In the ReactDOM.render function we create and pass in our Cat component and the root DOM node 'app'. We use createElement with our Cat component as the type, and an object with the name property as our props. In the Cat component itself we pass in a h1 tag as a string, and a template literal as a child.
Using React.createElement:
import React from "react";
import ReactDOM from "react-dom";
class Cat extends React.Component {
render() {
return React.createElement("h1", null, `My name is ${this.props.name}`);
}
}
ReactDOM.render(
React.createElement(Cat, { name: "Fishguts" }, null),
document.getElementById("app")
);
Hope you have come away with a better understanding of what happens when you write JSX in your React apps!
If you have any questions, comments, or feedback - please let me know. Follow for new weekly posts about JavaScript, React, Python, and Django!
Top comments (2)
Great explanation!
Thank you!