13 Feb 2024




Beginner

JSX stands for JavaScript XML. It's an extension syntax for JavaScript often used with React, a popular JavaScript library for building user interfaces. JSX allows developers to write HTML-like code directly within JavaScript code, making it easier to describe the structure of UI components.

With JSX, developers can write code that looks like a combination of HTML and JavaScript. For example:

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

In the above example, <h1>Hello, world!</h1> looks like HTML but is actually JSX code that will be transformed into regular JavaScript by a tool like Babel before it's executed in the browser.

JSX allows developers to write UI components more intuitively and efficiently. It's one of the key features that has contributed to the popularity of React for building modern web applications.

Examples of JSX:

Example 1: Rendering a Simple Component

const Greeting = () => {
  return <h1>Hello, world!</h1>;
};

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

Explanation:

  • This example defines a functional component Greeting using JSX syntax. The component returns a JSX element <h1>Hello, world!</h1>.
  • ReactDOM.render() is then used to render the Greeting component to a DOM element with the ID 'root'.

Example 2: Conditional Rendering

const App = ({ isLoggedIn }) => {
  return (
    <div>
      {isLoggedIn ? (
        <p>Welcome, user!</p>
      ) : (
        <p>Please log in.</p>
      )}
    </div>
  );
};

ReactDOM.render(
  <App isLoggedIn={true} />,
  document.getElementById('root')
);

Explanation:

  • In this example, the App component takes a prop called isLoggedIn.
  • JSX allows for conditional rendering using JavaScript expressions inside curly braces {}. If isLoggedIn is true, it renders "Welcome, user!"; otherwise, it renders "Please log in.".

Example 3: Using JSX with Arrays

const App = () => {
  const items = ['Apple', 'Banana', 'Orange'];

  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
};

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

Explanation:

  • This example demonstrates how JSX can be used with arrays and the map() function to dynamically render a list of items.
  • JSX allows embedding JavaScript expressions inside curly braces {}. Here, items.map() iterates over the array and generates a list of <li> elements with the array items as their content.
  • Each <li> element has a key attribute set to the index of the item, which helps React identify each list item uniquely when rendering lists efficiently.

These examples illustrate how JSX simplifies the process of writing UI components in React by allowing developers to use a syntax that closely resembles HTML.