Thursday, June 27, 2024

React JSX

What is JSX?
JSX stands for JavaScript XML. It's a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. JSX makes it easier and more intuitive to define the structure and appearance of UI components in React applications.

With JSX, you can write code that looks similar to HTML, but it's actually JavaScript under the hood. JSX elements can represent HTML elements, React components, or fragments.

JSX is eventually transpiled into JavaScript code with the help of Babel like transpiler.

Here's an example of JSX code:

import React from "react";

// JSX element representing a React component
const MyComponent = () => {
  return (
    <div>
      <h1>Hello, World!</h1>
      <p>This is a JSX element.</p>
    </div>
  );
};

export default MyComponent;

In this example:

  • The HTML-like '<div>', '<h1>', and '<p>' elements are JSX elements which are given in return statement.
  • The 'MyComponent' function returns JSX, which represents the structure of the component's UI.
  • JSX elements can contain plain text, other JSX elements, JavaScript expressions, or React components.
  • JSX is compiled to JavaScript using a tool like Babel before being executed by the browser.

JSX allows you to write more declarative and expressive code when building UI components in React, making it easier to understand and maintain your codebase.
Example1:

import React from "react";

// JSX element representing a React component
const MyComponent = () => {
  return (
    <div>
      <h1>Hello, World!</h1>
      <p>This is a JSX element.</p>
    </div>
  );
};

export default MyComponent;

Example2:

import React from "react";

// JSX element representing a React component
const MyComponent = () => {
  return (
    <>
      <h1>Hello, World!</h1>
      <p>This is a JSX element.</p>
    </>
  );
};

export default MyComponent;

Example3:

import React from "react";

// JSX element representing a React component
const MyComponent = () => {
  return (
    <React.Fragment>
      <h1>Hello, World!</h1>
      <p>This is a JSX element.</p>
    </React.Fragment>
  );
};

export default MyComponent;

React Fragments
The above examples provided are valid JSX syntax, but they have a slight difference in how they define a React fragment.

Example1. Using '<div>' as a Wrapper: In this example, the JSX is wrapped inside a '<div>' element, which acts as a wrapper for the JSX elements. This is a common approach when you need to wrap multiple JSX elements in a single parent element.

Example2. Using a Fragment ('<>...</>'): In this example, a React fragment is used to wrap the JSX elements. Fragments allow you to group multiple JSX elements without introducing an additional DOM element. They are useful when you don't want to add extra nodes to the DOM but still need a parent-like container for your JSX elements.

Example3. Using a Fragment ('<React.Fragment>...</React.Fragment>'): This example is similar to Example2 but it is more explicit.

Conclusion:

All three approaches are valid and have their use cases. The choice between using a '<div>' wrapper or a fragment depends on your specific requirements and preferences. If you need a wrapper element for styling or structural reasons, you can use a '<div>'. If you want to avoid adding unnecessary elements to the DOM, you can use a fragment.

In above examples, we have used simple HTML-like text as JSX. In the following sections, we will see how to intersperse JavaScript code inside JSX.

JavaScript with JSX

In JSX, you can intersperse JavaScript code using curly braces '{}'. This allows you to embed JavaScript expressions, variables, or function calls directly within your JSX markup.

Here are some examples:

1. Embedding JavaScript Expressions:


import React from 'react';

const MyComponent = () => {
  const name = 'John';
  const greeting = 'Hello, ${name}!';

  return (
    <div>
      <p>{greeting}</p>
      <p>{2 + 2}</p>
    </div>
  );
};

export default MyComponent;

In this example, we use curly braces '{}' to embed JavaScript expressions ('greeting' and '2 + 2') directly within the JSX markup.

2. Using Variables:


import React from 'react';

const MyComponent = () => {
  const items = ['apple', 'banana', 'orange'];

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

export default MyComponent;
In this example, we use curly braces '{}' to embed a JavaScript expression inside the 'map()' function call, allowing us to dynamically generate a list of JSX elements based on an array of items.

3. Calling Functions:
import React from 'react';

const MyComponent = () => {
  const formatName = (firstName, lastName) => {
    return '${firstName} ${lastName}';
  };

  return (
    <div>
      <p>Hello, {formatName('John', 'Doe')}!</p>
    </div>
  );
};

export default MyComponent;
In this example, we use curly braces '{}' to call the 'formatName()' function and pass it arguments directly within the JSX markup.
Using curly braces '{}' allows you to seamlessly integrate JavaScript code within your JSX markup, making it easy to create dynamic and interactive UIs in React.

JSX Attributes
In React, JSX attributes are written in camel case. This means that attribute names in JSX follow the camel case convention, not the traditional kebab-case (dash-separated) convention commonly used in HTML.

For example, in HTML, you might write an attribute like 'class' and background-color as follows:
<div class="container" background-color="cyan">
  <!-content goes here -->
</div>

In JSX, however, you would write the same attributes as 'className' and backgroundColor:
<div className="container" backgroundColor="cyan">
  {/* content goes here */}
</div>

Similarly, other attributes follow the camelCase convention: 'tabindex' becomes 'tabIndex', 'for' becomes 'htmlFor', 'onclick' becomes 'onClick' etc.

This camelCase convention is a requirement in JSX to avoid conflicts with JavaScript reserved words (such as 'class'), and to maintain consistency with JavaScript naming conventions. When JSX is compiled, these camel case attributes are transformed into their kebab-case counterparts as expected by the DOM.

Loop in JSX
You can use JavaScript loops in JSX to dynamically render components or content based on an array or any iterable data structure. You typically use JavaScript map, forEach, or other loop methods within curly braces {} to iterate over data and generate JSX elements.

Here's an example of using a loop to render a list of items in JSX:
import React from 'react';

function MyComponent() {
  const items = ['apple', 'banana', 'cherry'];

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

export default MyComponent;
In this example, the map function is used to iterate over the items array and generate <li> elements for each item. The key prop is important to provide React with a unique identifier for each list item.

No comments:

Post a Comment

Hot Topics