Tuesday 29 October 2024

Understanding Components and JSX in React

 

In this post, I am going to talk about components in detail with an example.

 

What is a Component in React?

In React, components are the building blocks of the UI (User Interface). You can think of them as reusable pieces of code that represent parts of the interface, like buttons, forms, or even entire sections of a web page. A component can have its own HTML structure, styling, and behavior.

 

In simple terms, a component,

 

1.   Renders UI elements: It defines how a particular part of the UI should look.

2.   Handles state: It can hold and manage data that might change (like a user input).

3.   Is reusable: You can create one component and use it multiple times across your app.

 

Components allow us to break the UI into smaller, reusable pieces. For example, if you create a button as a component, you can use that same button anywhere in the app without writing the code again. Each component focuses on a specific task. This makes code modular and easier to maintain, debug, and understand.

 

Components can be nested within other components, making it easier to build more complex UIs out of simpler ones. When applications grow, using components makes it easier to manage complex UIs by breaking them into simpler, self-contained units.

 

Follow step-by-step procedure to start developing your first React Component.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘my-first-react-component’.

 

Project structure looks like below.

 


Step 2: Open src/main.jsx file and replace the content with below code.

 

main.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'

// Define a component called 'HelloWorld'
function HelloWorld() {
  return <h1>Building UI Applications using React is Fun...........</h1>; // JSX to return an h1 element
}

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <HelloWorld />
  </StrictMode>,
)

Step 3: Build and run the application by executing below commands.

cd my-first-react-component
npm install
npm run dev

Open the url ‘http://localhost:5173/’, you will see below screen.




Explanation

1. index.html is the starting point to this application. Open index.html page, you can observe below snippet.

<body>
  <div id="root"></div>
  <script type="module" src="/src/main.jsx"></script>
</body>

 

<div id="root"></div> : This is the main element where React will render your entire application. In a React app, there is typically one single root element (<div id="root">) in the HTML file. React will take over this empty <div> and dynamically inject all the content of the React components into it.

 

<script type="module" src="/src/main.jsx"></script>

 

This line tells the browser to load and run the JavaScript file that contains your React code. Using the type="module" attribute means the script will be treated as a modern JavaScript ES6 module, which also supports features like import and export. This is essential for React apps since they often use ES6 module imports to include components, libraries, and other code.

 

src="/src/main.jsx"

This specifies the source file that contains your React code, in this case, the file main.jsx.

 

2. main.jsx file

 

main.jsx

 

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'

// Define a component called 'HelloWorld'
function HelloWorld() {
  return <h1>Building UI Applications using React is Fun...........</h1>; // JSX to return an h1 element
}

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <HelloWorld />
  </StrictMode>,
)

 

import { StrictMode } from 'react'

import { createRoot } from 'react-dom/client'

StrictMode: This is a built-in feature of React used to highlight potential issues in the code during development. It doesn’t render anything to the screen but helps you write better code by warning you about deprecated or unsafe practices. It’s typically used to ensure that the app follows the best practices. When your app runs in StrictMode, React may give warnings in the console, especially for things that could cause problems in the future.

 

createRoot: createRoot is a method from react-dom/client. It is used to create a root container for your React application. It essentially connects React to the real DOM (the structure of a webpage) so that React can start rendering components to the page.

 

HelloWorld Component

function HelloWorld() {
  return <h1>Building UI Applications using React is Fun...........</h1>;
}

 

Above snippet defines a React component named HelloWorld. In React, components can be defined as functions. Here, HelloWorld is a simple function that returns some JSX.

 

The component returns JSX: <h1>Building UI Applications using React is Fun...........</h1>. This looks like HTML but is actually JavaScript code written in JSX (JavaScript XML).

 

Rendering Component to the DOM

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <HelloWorld />
  </StrictMode>,
)

createRoot(document.getElementById('root'))

This command selects an element from the HTML page (usually the index.html file) with the id="root". This is the placeholder where React will inject its content.

 

.render()

The render() method is called to render your React components into the root element (the div with id="root" in the HTML). In this example, it displays the HelloWorld component on the webpage.

 

<StrictMode>

The HelloWorld component is wrapped in <StrictMode>. This is an extra layer of safety that ensures your component follows best practices. It doesn’t affect how the component is rendered but ensures React applies checks during development.

 

<HelloWorld />

This is the actual React component that you’ve created. It gets displayed on the page by calling render(). In React, components are usually written in self-closing tags like <HelloWorld />. This tells React to insert the content of the HelloWorld component at this position.

 

 

You can download this application from this link.


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment