Rendering React Components
Rendering Components means turning your component code into the UI that users see on the screen.
React is capable of rendering user-defined components. To render a component in React we can initialize an element with a user-defined component and pass this element as the first parameter to ReactDOM.render() or directly pass the component as the first argument to the ReactDOM.render() method.
The below syntax shows how to initialize a component to an element:
const elementName = <ComponentName />;
In the above syntax, the ComponentName is the name of the user-defined component.
Note: The name of a component should always start with a capital letter. This is done to differentiate a component tag from an HTML tag.
Example: This example renders a component named Welcome to the Screen.
// Filename - src/index.js:
import React from "react";
import ReactDOM from "react-dom";
// This is a functional component
const Welcome = () => {
return <h1>Hello World!</h1>;
};
ReactDOM.render(
<Welcome />,
document.getElementById("root")
);
Output: This output will be visible on the http://localhost:3000/ on the browser window.
Explanation:
Let us see step-wise what is happening in the above example:
- We call the ReactDOM.render() as the first parameter.
- React then calls the component Welcome, which returns <h1>Hello World!</h1>; as the result.
- Then the ReactDOM efficiently updates the DOM to match with the returned element and renders that element to the DOM element with id as “root”.
React Components
Components in React serve as independent and reusable code blocks for UI elements. They represent different parts of a web page and contain both structure and behavior. They are similar to JavaScript functions and make creating and managing complex user interfaces easier by breaking them down into smaller, reusable pieces.