sajad torkamani

JSX (JavaScript XML) is an XML-like syntax that compiles to JavaScript. When used in React, it provides syntactic sugar for the React.createElement(component, props, ...children) function.

JSX compiles into JavaScript

The following JSX code:

<MyButton color="blue" shadowSize={2}>
  Click Me
</MyButton>

compiles into:

React.createElement(
  MyButton,
  {color: 'blue', shadowSize: 2},
  'Click Me'
)

You can use the Babel REPL to see how JSX compiles into JavaScript.

JSX is optional in React

JSX is just syntactic sugar for various React APIs. So, you could build an entire React app without using JSX. Here’s an example (CodeSandbox):

import React from 'react'
import { createRoot } from 'react-dom/client'

class App extends React.Component {
  render() {
    return React.createElement('div', null, `Hello ${this.props.name}`)
  }
}

const rootElement = document.getElementById('root')
const root = createRoot(rootElement)

root.render(React.createElement(App, { name: 'Sajad' }, null))

Sources

Tagged: React

Leave a comment

Your email address will not be published. Required fields are marked *