React JSX
π± This post is in the growth phase. It may still be useful as it grows up.
JSX is weird.
Itβs kinda like HTML but mostly not. And like most abstractions that are kinda like something else, itβs easy to accidentally do things the wrong way.
This page is a collection of JSX truths to keep in mind when debugging React.
What is JSX?
JSX is a syntax extension for JavaScript. It gives React that doughy familiar feeling of HTML. But it is not valid JavaScript. Which means that it canβt run in a browser without first transforming that JSX into JavaScript.
Reference: JSX introduction and specification, facebook.github.io/jsx.
How does JSX work?
Using a superset language (like TypeScript) or a JavaScript compiler (like Babel), JSX syntax is transformed into React.createElement
calls.
<div>Hello common component!</div>
/* πππ TypeScript or Babel Transformation πππ */
React.createElement("div", null, "Hello common component!");
Hereβs another with few props.
<div id="user_greeting" className="greeting"> Hello common component!</div>
/* πππ TypeScript or Babel Transformation πππ */
React.createElement( "div", { id: "user_greeting", class: "greeting" }, "Hello common component!");
Custom component example
React.createElement(MyComponent, "Hello common component!");<MyComponent>Hello common component!</MyComponent>;
Component with props
With JSX
let reactElement = ( <MyComponent className="my-css-class-selector" name="React Rally" />);function MyComponent({ name, ...restProps }) { return <h1 {...restProps}>Hello {name}</h1>;}
Unlike everything we covered in React Basics, JSX requires some form of build step.
JSX must be transformed into React.createElement
calls befor the browser can run it.
Why does JSX exist?
The line is that it gives designers and developers a familiar HTMl-like syntax.
Use curly braces to interpolate values
This is also true for attributes
Every JSX element can be self-closing
Canβt copy paste HTML without transformation
React components are just functions that return React elements. Declare a new component and use it to create our React element.
let domNode = document.getElementById("root");// 2. Create a React element from a the new componentlet reactElement = React.createElement("h1", {}, "Hello React");let reactElement = React.createElement(MyComponent);// 1. Declare a new componentfunction MyComponent() { return React.createElement("h1", {}, "Hello React Component");}ReactDOM.createRoot(domNode).render(reactElement);
Reference: Your first component, react.dev.