React JSX (JavaScript XML)

In create react app, and other articles, if you observe, we are writing HTML-like code in our React code. However, this is not standard HTML, this is JSX, which stands for JavaScript XML.

 

JSX is an extension to JavaScript syntax that allows you to write HTML-like code within your JavaScript files in React. It's a key feature of React that simplifies the creation of UI components and enhances their readability.

 

At first glance, JSX might look like HTML, but it's important to note that JSX is not HTML. It's a syntax extension of JavaScript that gets transformed into JavaScript code before being rendered by the browser.

 

In React, it’s not mandatory to use JSX to write the code. If you don’t want to use JSX, then you need to use React inbuilt createElement function. This function will accept the component tag, object properties, and child components to render the content same as JSX.

 

Following are examples of writing the code in React with JSX and without JSX so that you will have an idea of how JSX makes it easier to write HTML code in React.

Without JSX

The following is an example of writing HTML without JSX.

 

function Greeting() {
// Without JSX
return React.createElement("div",{className:"App"},React.createElement("h1",{},"Hello, React!"));
}

In this example, we are explicitly using React.createElement function to define the HTML elements in React.

With JSX

The following is an example of using JSX to write the HTML in React code.

 

function Greeting() {
// With JSX
return (<div className="App"><h1>Hello, React!</h1></div>);
}

In this example, JSX simplifies the process by allowing us to write HTML directly within the JavaScript code.

 

Behind the scenes, JSX also will use React.createElement function. The opening tag <div> corresponds to React.createElement('div', {}, ...) and the opening tag <h1> corresponds to React.createElement('h1', {}, 'Hello, React!'). Instead of worrying about all these things, we can directly write HTML-like code inside of JavaScript.

 

In React, to write code using JSX, you need to be aware of certain rules and details about JSX, otherwise, you may encounter exceptions while building your application. Before proceeding, ensure you have created the React app. If you are not aware of it, you can refer to the create react app guide.

 

Note: The code changes suggested in this article are to be made in the App.js file.

Single Parent Element

If you wish to return multiple elements in JSX, it is expected that there should be one parent element that wraps around those elements. If you try to return multiple HTML elements without using any parent element like <div> you will get an exception.

 

function App() {
  return (
    <h1>Heading 1</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
  );
}

The above code will throw an exception like “App.js Line 7:6:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?”. To fix this problem, you need to wrap all the HTML elements within a single parent element, like <div>, as shown below.

 

function App() {
  return (
    <div>
      <h1>Heading 1</h1>
      <p>Paragraph 1</p>
      <p>Paragraph 2</p>
    </div>
  );
}

The above code will fix the problem of rendering multiple elements, but it will add an extra <div> element to your design. If you prefer not to include that extra wrapper element, you can enclose all your HTML elements using <> and </>, as shown below.

 

function App() {
  return (
    <>
      <h1>Heading 1</h1>
      <p>Paragraph 1</p>
      <p>Paragraph 2</p>
    </>
  );
}

In React, an empty HTML tag (<> </>) is called a fragment. Fragments will allow you to group multiple elements without adding any extra nodes in the DOM. To learn more about fragments in React, visit React Fragments.

Close All the Tags

Since JSX follows XML rules, you need to ensure that all HTML tags are closed properly otherwise you will get an exception.

 

function App() {
  return (
    <div>
      <h1>Welcome to My Website!</h1>
      <img src="image.jpg" alt="My Image" />
      <p>This is a sample paragraph.</p>
      <input type="text" />
    </div>
  );
}

Comments in JSX

JSX supports JavaScript-style comments. If you want to add comments, those should be wrapped within the curly braces {/* */}, as shown below.

 

function App() {
  return (
    <div>
      <h1>Hello, JSX!</h1>
      {/* This is a comment */}
    </div>
  );
}

Writing Expressions in JSX

If you want to include JavaScript expressions in JSX, you can use curly braces {}. These expressions can be variables, function calls, or any valid JavaScript code.

 

function App() {
  const name = 'John Doe';
  const age = 25;

  return (
    <div>
      <h1>{name}</h1>
      <p>{`Age: ${age}`}</p>
    </div>
  );
}

Attributes and Props in JSX

JSX allows you to assign attributes to elements, similar to HTML. However, in JSX, attributes are referred as props (short for properties) and are written using the camelCase naming convention.

 

This means that instead of using hyphenated attribute names like in HTML, we use camelCase for attribute names in JSX.

 

For example, in HTML, we will write the code as below.

 

<div class="my-class"></div>

 However, in JSX, we would write as below.

 

<div className="my-class"></div>

As you can see, the attribute class in HTML becomes className in JSX.

 

Similarly, other HTML attributes follow the same pattern. For instance:

  • tabindex becomes tabIndex
  • for becomes htmlFor
  • maxlength becomes maxLength

By using camelCase, JSX ensures consistency with JavaScript naming conventions. It also helps differentiate between HTML attributes and React component-specific props.

 

It’s important to remember to use camelCase when assigning props to elements in JSX to ensure that your code is valid and consistent, as shown in the following example.

 

import React from 'react';

function App() {
const name = 'John Doe';

// Using camel case for attributes (props)
return (
    <div className="container">
      <h1>Welcome, {name}!</h1>
      <input type="text" value={name} onChange={handleChange} />
    </div>
  );
}

function handleChange(event) {
  // Handle input change event
  console.log('Input value:', event.target.value);
}

export default App

Styling in JSX

We can apply inline styles to JSX elements using the style prop. The style should be specified as a JavaScript object, where the CSS property names are written in camelCase. In the following example, we’ve created our own component (MyComponent). To render the component, open your index.js file and replace its content with the following code. To learn more about components, you can refer to the React Components article.

 

import React from 'react';
import ReactDOM from 'react-dom';

function MyComponent() {
  const styles = {
    color: 'red',
    fontSize: '16px',
    fontWeight: 'bold',
  };

  const className = 'my-class';

  return (
    <div>
      <h1>Welcome to My Website!</h1>
      <p style={styles}>Styled Text</p>
      <p className={className}>Element with Class</p>
    </div>
  );
}

ReactDOM.render(<MyComponent />, document.getElementById('root'));

Conditional Statements in JSX

Conditional statements are essential for creating dynamic user interfaces. When it comes to conditional rendering in JSX, there are multiple approaches that we will cover in the coming topics. One common approach is to use an if-else statement within a functional component.

 

function Login({isLoggedIn}){
  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please log in.</h1>;
  }
}
export default function Greeting() {
  return(<Login isLoggedIn={true} />);
}

This is how we can use JSX in React to write HTML-like code inside the JavaScript files, keeping both rendering logic and content in the same place based on our requirements.