Module: JSX and Rendering

Rendering Elements

React JS: JSX and Rendering - Rendering Elements

What is Rendering?

Rendering in React is the process of converting React components into actual DOM (Document Object Model) elements that are displayed in the browser. React uses a virtual DOM to efficiently update the real DOM, minimizing performance bottlenecks.

JSX: JavaScript XML

JSX is a syntax extension to JavaScript that allows you to write HTML-like code within your JavaScript files. It's not HTML, but it's transformed into regular JavaScript function calls that create React elements.

Key Features of JSX:

  • HTML-like Syntax: Makes UI code more readable and maintainable.
  • Expressions: You can embed JavaScript expressions within JSX using curly braces {}.
  • Attributes: HTML attributes are written as camelCase in JSX (e.g., className instead of class).
  • Self-Closing Tags: Tags that don't have closing tags in HTML (like <br>, <img>, <input>) must be self-closed in JSX (e.g., <br />, <img src="image.jpg" />).

Example:

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

This JSX code will be transformed into something like:

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

Rendering React Elements

React elements are plain JavaScript objects that describe what you want to see on the screen. They are immutable. To display a React element, you need to use the ReactDOM.render() method (or createRoot in newer React versions).

ReactDOM.render() (Legacy - React < 18):

import ReactDOM from 'react-dom/client';

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

ReactDOM.render(element, document.getElementById('root'));

This code renders the <h1>Hello, world!</h1> element into the DOM element with the ID "root".

createRoot() (React 18+):

import ReactDOM from 'react-dom/client';

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

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(element);

This is the recommended approach for React 18 and later. It provides concurrent rendering features.

Rendering Components

You can also render React components. Components are reusable pieces of UI.

Functional Component:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(element);

Class Component (Less common in modern React):

import React from 'react';

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

const element = <Welcome name="Sara" />;

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(element);

Rendering Multiple Elements

JSX expressions must have a single top-level element. If you need to render multiple elements, you can wrap them in a fragment:

Using <React.Fragment>:

import React from 'react';

function MyComponent() {
  return (
    <React.Fragment>
      <h1>First Heading</h1>
      <p>Some paragraph.</p>
    </React.Fragment>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyComponent />);

Using <> (Shorthand Fragment):

function MyComponent() {
  return (
    <>
      <h1>First Heading</h1>
      <p>Some paragraph.</p>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyComponent />);

Rendering Conditional Content

You can conditionally render content using JavaScript expressions within JSX.

Using if statements (within a function):

function MyComponent(props) {
  if (props.isLoggedIn) {
    return <h1>Welcome back!</h1>;
  }
  return <h1>Please sign up.</h1>;
}

Using Ternary Operator:

function MyComponent(props) {
  return (
    <h1>{props.isLoggedIn ? 'Welcome back!' : 'Please sign up.'}</h1>
  );
}

Using Logical AND (&&) Operator:

function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn && <p>You are logged in.</p>}
    </div>
  );
}

Rendering Lists

To render lists of data, use the map() method to iterate over an array and create a React element for each item. Important: Each element in the list must have a unique key prop.

function MyList(props) {
  const items = props.items;
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

const items = [
  { id: 1, name: 'Apple' },
  { id: 2, name: 'Banana' },
  { id: 3, name: 'Orange' },
];

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyList items={items} />);

Key Prop: The key prop helps React identify which items have changed, are added, or are removed. It should be a unique and stable identifier for each item in the list. Using the index of the array as a key is generally discouraged unless the list is static and never changes.