React JSX

Summary: in this tutorial, you will learn about React JSX and how to write JSX elements properly in React applications.

Introduction to the React JSX #

JSX stands for JavaScript XML.

JSX provides a syntax extension for JavaScript that allows you to write HTML-like code directly within JavaScript.

JSX offers expressive syntax that simplifies the process of building user interfaces in React applications by combining the strength of JavaScript and the simplicity of HTML.

Before returning a response to the web browser, React uses Babel to transpile JSX into native JavaScript code.

Returning valid JSX #

If you want to return a single line of JSX, you can put the opening tag of the JSX block on the same line as the return statement. For example:

const App = () => {
  return <h1>Hello, React!</h1>;
};

Additionally, you can use a set of parentheses () to wrap the JSX. In this case, the opening parenthesis ( must be on the same line as the return statement:

const App = () => {
  return (
    <div>
      <h1>Hello, React!</h1>
    </div>
  );
};

Notice that if you don’t put the opening parenthesis on the same line as the return statement, JavaScript will assume that the function returns undefined.

If you return multiple JSX elements, you must wrap them with a containing element such as a div. For example:

const App = () => {
  return (
    <div>
      <h1>Hello, React!</h1>
      <p>I love React.</p>
    </div>
  );
};

In this example, we use a div to wrap the h1 and p elements.

You’ll encounter a compiled error if you don’t wrap these elements inside a containing element. For example, the following code will result in an error:

const App = () => {
  return (
      <h1>Hello, React!</h1>
      <p>I love React.</p>
  );
};

If you don’t want to use containing elements because they may conflict with CSS rules, you can wrap them in an empty JSX element:

const App = () => {
  return (
    <>
      <h1>Hello, React!</h1>
      <p>I love React.</p>
    </>
  );
};

The empty brackets are called a React Fragment.

Writing JSX elements #

JSX inherits the syntax from the HTML, therefore, you can write JSX like HTML. For example:

<p>This is a message</p>

Some HTML elements are self-closing such as <input> element. In this case, you need to add the forward-slash (/) at the end of the opening tag:

<input type="text" />

Using variables in JSX #

To show a JavaScript variable in JSX, you can wrap it with curly braces. For example:

const App = () => {
  const name = 'John';
  return <p>Hello, {name}!</p>;
};

In this example, we declare a variable name and initialize its value to 'John'. Additionally, we use the name variable inside the JSX.

The component will output the following HTML:

<p>Hello, John!</p>

JSX can display strings and numbers. For example:

const App = () => {
  const name = 'John';
  const age = 25;
  return (
    <p>
      Hi, I'm {name}. I'm {age} years old.
    </p>
  );
};

Output:

Hi, I'm John. I'm 25 years old.

But JSX cannot display a boolean (true, false), null, undefined:

const App = () => {
  const name = 'John';
  const age = 25;
  const active = true;
  let jobTitle = null;

  return (
    <ul>
      <li>Name: {name}</li>
      <li>Age: {age}</li>
      <li>Status: {active}</li>
      <li>Job Title: {jobTitle}</li>
    </ul>
  );
};

Output:

  • Name: John
  • Age: 25
  • Status:
  • Job Title:

When displaying a JavaScript array, JSX concatenates all the elements into a single string:

const App = () => {
  const name = 'John';
  const skills = ['JS', 'React', 'Node.js'];

  return (
    <ul>
      <li>Name: {name}</li>
      <li>Skills: {skills}</li>
    </ul>
  );
};

Output:

  • Name: John
  • Skills: JSReactNode.js

In this example, JSX concatenates JS, React, and Node.js into a single string JSReactNode.js and displays it.

It’s also important to note that JSX cannot display a JavaScript object. If you attempt to do so, you will encounter an error in the web browser. For example:

const App = () => {
  const person = {
    name: 'John',
    age: 25,
  };
  return <p>{person}</p>;
};

Error:

Uncaught Error: Objects are not valid as a React child (found: object with keys {name, age}). If you meant to render a collection of children, use an array instead.

Using expressions in JSX #

To use an expression in JSX, you place it within a pair of curly braces. For example:

const App = () => {
  const name = 'John';
  const age = 25;
  const active = true;

  return (
    <ul>
      <li>Name: {name}</li>
      <li>Age: {age}</li>
      <li>Status: {active ? 'Active' : 'Inactive'}</li>
    </ul>
  );
};

Output:

  • Name: John
  • Age: 25
  • Status: Active

In this example, we use a ternary operator (?:) to return different strings based on the value of the active variable:

<li>Status: {active ? 'Active' : 'Inactive'}</li>

Adding element props #

In React, attributes of a JSX element are called props.

JSX allows you to assign any props to a JSX element. However, if a prop accepts a string, you must wrap it in double quotes. For example:

const App = () => {
  return (
    <form>
      <div>
        <label for="event">Event Name: </label>
        <input name="event" type="text" />
      </div>
      <div>
        <label for="event">Event Date: </label>
        <input name="email" type="date" />
      </div>
      <div>
        <button type="submit">Submit</button>
      </div>
    </form>
  );
};

Output:

If you assign a JavaScript variable to a prop, you don’t use double quotes but only curly braces when doing it:

const App = () => {
  const type = 'range';
  return (
    <div>
      <label for="zoom">Zoom Level:</label>
      <input id="zoom" name="zoom" type={type} min="0" max="100" />
    </div>
  );
};

Output:

Applying CSS #

In JavaScript, the class is a keyword that defines a class. Therefore, you cannot use the class keyword as a prop of a JSX element. Instead, you use the className. For example:

const App = () => {
  return (
    <button className="btn" type="button">
      OK
    </button>
  );
};

Output:

To add an inline style to a JSX element, you define a JavaScript object with properties that are the same as the CSS properties.

However, if a property has a dash in its name such as margin-top, background-color, you need to remove the dash (-) and capitalize the next letter. For example:

const App = () => {
  return (
    <button
      type="button"
      style={{
        padding: '0.25rem 0.75rem',
        backgroundColor: '#F9DC5C',
        border: 'None',
        display: 'inline-block',
        minWidth: '80px',
        cursor: 'pointer',
      }}
    >
      OK
    </button>
  );
};

Output:

Notice that there are two pairs of curly braces in the value of the style prop:

  • The outer pair indicates that we are about to use JavaScript in JSX.
  • The inner pair denotes the JavaScript object.

The following component displays the same button but uses the value of the style prop as a variable that holds a JavaScript object:

const App = () => {
  const btnStyle = {
    padding: '0.25rem 0.75rem',
    backgroundColor: '#F9DC5C',
    border: 'None',
    display: 'inline-block',
    minWidth: '80px',
    cursor: 'pointer',
  };
  return (
    <button type="button" style={btnStyle}>
      OK
    </button>
  );
};

Similarly, the for is a keyword in JavaScript, you cannot use it as a prop for a <label> element:

<label for="email">
    <input type="email" id="email" />
</label>

Instead, you use the htmlFor prop:

<label htmlFor="email">
    <input type="email" id="email" />
</label>

Summary #

  • JSX stands for JavaScript XML
  • JSX is a syntax extension to JavaScript that allows you to write HTML-like code directly inside JavaScript code.
  • JSX helps you speed up building UI for React applications.

Was this helpful?