Skip to main content

JSX

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like elements and components in a JavaScript file. It's mainly used with React to describe what the UI should look like. JSX provides a more concise and readable way to create and manage the DOM elements in JavaScript.

Basic Syntax

JSX looks similar to HTML, but there are some differences. For example, the class attribute in HTML is written as className in JSX.

const element = <h1 className="greeting">Hello, world!</h1>;

How It Works

  1. Transpilation: JSX is not understood by the browser. It needs to be transpiled into regular JavaScript using tools like Babel. For example, the JSX element above would be transpiled to:

    const element = React.createElement('h1', { className: 'greeting' }, 'Hello, world!');
  2. React Elements: The React.createElement function returns a React element, which is a lightweight description of what the DOM should look like. React elements are immutable.

  3. Rendering: React elements are then rendered to the actual DOM by ReactDOM or a similar rendering engine. This is usually done in the index.js file of a React application.

    ReactDOM.render(element, document.getElementById('root'));
  4. Reconciliation: When the state or props of a component change, a new React element tree is created. React then compares this new tree with the old one (a process called "Reconciliation") and updates the DOM to match the new tree.

Embedding Expressions

You can embed JavaScript expressions in JSX by wrapping them in curly braces {}.

const name = 'John';
const element = <h1>Hello, {name}</h1>;

Components

JSX allows you to define and use React components. Components can either be defined as functions or classes and can be rendered inside other JSX elements.

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

const element = <Welcome name="John" />;

Self-closing Tags

In JSX, all tags must be closed. If an element doesn't have any children, you can use the self-closing tag syntax.

const element = <img src="image.jpg" alt="Description" />;

Conditional Rendering

JSX works seamlessly with JavaScript logic for conditional rendering of elements, often using ternary operators, logical AND (&&), or even JavaScript functions to determine what to render.

const isLoggedIn = true;
const element = isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>;

Looping

You can use JavaScript's map function to loop through arrays and render multiple elements.

const numbers = [1, 2, 3];
const listItems = numbers.map((number) => <li key={number}>{number}</li>);

JSX provides a powerful and intuitive way to create React elements and components, making it easier to build and manage complex UIs.