React  

What is JSX in React?

JSX is a syntax that lets JavaScript and HTML coexist in the same file. It lets you write HTML-like code inside JavaScript, which React then transforms into real JavaScript function calls using React.createElement()

So instead of writing

const element = React.createElement('h1', null, 'Hello, React!');

You can write this

const element = <h1>Hello, React!</h1>;

Both produce the same thing, a React element (an object describing the DOM).

How does it work behind the Scenes?

JSX in React App
  • You write JSX, e.g. <div>Hello</div>

  • The Babel compiler converts it into:

React.createElement('div', null, 'Hello');
  • React uses this to build the Virtual DOM tree.

  • React renders the actual elements to the Real DOM efficiently.

Example with a Component

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

When compiled, it becomes roughly:

function Welcome(props) {
  return React.createElement('h1', null, `Hello, ${props.name}`);
}