[React] What is JSX?

·

3 min read

[React] What is JSX?

JSX, or JavaScript XML, is a syntax extension for JavaScript recommended by React for creating React elements. It looks similar to XML or HTML, making it more readable and intuitive when describing the structure of your UI components.

In essence, JSX provides a syntactic sugar for the React.createElement(component, props, ...children) function, allowing developers to write React components in a more concise and HTML-like syntax.


JSX vs JavaScript

Let's take a look at a simple example to understand how JSX differs from traditional JavaScript.

JavaScript:

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

JSX:

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

In the JSX example, it's clear that we are defining a React element that represents an <h1> heading with the content "Hello, React!". This syntax is not only more readable but also resembles HTML, making it easier for developers to building components with React.


Embedding Expressions

One of the strengths of JSX is its ability to embed JavaScript expressions within the markup. This allows dynamic content to be easily integrated into your components.

const name = 'John';
const greeting = <p>Hello, {name}!</p>;

In this example, the variable name is embedded within the JSX expression, resulting in a dynamic greeting that can easily change based on the value of name.


JSX Attributes

JSX also supports attributes, similar to HTML. These attributes are used to pass additional information to React elements.

const element = <a href="https://www.reactjs.org" target="_blank">Visit React's official website</a>;

In this example, the href and target attributes are used to create a link element. JSX attributes work similarly to HTML.


className instead of class

In JSX, the attribute for defining CSS classes is className instead of class. This is because class is a reserved keyword in JavaScript.

const myElement = <div className="my-class">This has a CSS class</div>;

Conditions with if Statements

You can use regular JavaScript if statements to conditionally render elements in JSX.

const isLoggedIn = true;

const Greeting = () => {
  if (isLoggedIn) {
    return <p>Welcome back!</p>;
  } else {
    return <p>Please log in to continue.</p>;
  }
};

// Usage
const greetingMessage = <Greeting />;

In this example, the Greeting component conditionally renders different messages based on the value of isLoggedIn.

Or you can use ternary expressions instead like this:

const isLoggedIn = true;

const greetingMessage = <p>{isLoggedIn ? "Welcome back!" : "Please log in to continue."}</p>;

Conclusion

In summary, JSX in React is a syntax extension that provides a more concise and readable way to create React elements. By resembling HTML and allowing the embedding of JavaScript expressions, JSX simplifies the process of building dynamic and interactive user interfaces.