Sage-Code Laboratory
index<--

Chapter 4: Rendering Components

In Chapter 4, we'll delve into the essential process of rendering components in React. This involves transforming your React component code into actual UI elements displayed on the web page.

Rendering Components in the DOM

The Document Object Model (DOM) is a hierarchical representation of your web page's structure. React interacts with the DOM to create and update UI elements based on your components.

Using the "ReactDOM.render" Function

React provides the "ReactDOM.render" function, a vital tool for rendering React components within the DOM. It takes two arguments:

  1. The component to render: This is the React component you want to display on the page. You can either pass the component itself or a JSX element representing the component.
  2. The container element (DOM element): This is the HTML element in your web page where you want the component to be displayed. You typically use the "document.getElementById" method to reference an existing element with a specific ID.

Here's an example of using "ReactDOM.render":


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

function Greeting() {
  return (
    <div>
      <h1>Hello, World!</h1>
    </div>
  );
}

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

In this example:

Nesting Components

React components can be nested within each other to create complex UI structures. A parent component can render child components, which in turn can render their own child components, and so on. This hierarchical structure allows you to build modular and reusable components.

For example, you might have a "NavBar" component containing a "Logo" component and a list of "Link" components.

We'll explore more advanced rendering techniques and component relationships in the following chapters. Stay tuned!


Read next: State Managemen