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

Understanding the typeof Operator in JavaScript with examples

The typeof operator in JavaScript is used to determine the type of a given value or variable. It returns a string indicating the type of the operand. The typeof operator is particularly useful for checking the data type before performing operations or when debugging code.

Syntax

typeof operand

 

operand: The value or variable whose type you want to check.

 

Let's go through the various data types in JavaScript and see what the typeof operator returns for each.

 

1. Primitive Types

String: A sequence of characters enclosed in quotes (single, double, or backticks).

 

string.js

let str = "Hello, World!";
console.log(typeof str); // Output: "string"

 

Output

String

 

Number: Represents both integers and floating-point numbers.

 

number.js

let num = 42;
console.log(typeof num); // Output: "number"

let floatNum = 3.14;
console.log(typeof floatNum); // Output: "number"

 

Output

number
number

 

Boolean: Represents a logical entity and can have two values: true or false.

 

boolean.js

let isActive = true;
console.log(typeof isActive); // Output: "boolean"

 

Output

boolean

 

Undefined: A variable that has been declared but not assigned a value.

 

undefined.js

let undefinedVar;
console.log(typeof undefinedVar); // Output: "undefined"

 

Output

undefined

 

Symbol: Introduced in ECMAScript 2015 (ES6), a Symbol is a unique and immutable primitive value.

 

symbol.js

 

let sym = Symbol('unique');
console.log(typeof sym); // Output: "symbol"

Output

symbol

BigInt: Introduced in ECMAScript 2020, BigInt is used for integers that are too large to be represented by the Number type.

 

bigint.js

let bigIntNum = 123456789012345678901234567890n;
console.log(typeof bigIntNum); // Output: "bigint"

Output

Bigint

 

2. Object Types

Object: A collection of key-value pairs. Objects include arrays, functions, dates, etc. Arrays are objects in JavaScript, so the typeof operator returns "object" for arrays as well. Functions are also objects in JavaScript, but the typeof operator returns "function" for functions. The typeof operator returns "object" for date objects as well.

 

objects.js

let obj = { name: "Alice", age: 30 };
console.log(typeof obj); // Output: "object"

let arr = [1, 2, 3, 4];
console.log(typeof arr); // Output: "object"

function greet() {
  return "Hello!";
}
console.log(typeof greet); // Output: "function"

let date = new Date();
console.log(typeof date); // Output: "object"

Output

object
object
function
object

Points to remember

1.   typeof null returns "object"

2.   Even though functions are technically objects, typeof treats them as a special case and returns "function".

3.   type of an undeclared variable returns "undefined"

 

Usecase 1: Checking for Numbers Before Performing Arithmetic Operations.

 

usecase1.js

function addNumbers(a, b) {
  if (typeof a !== "number" || typeof b !== "number") {
    throw new Error("Both arguments must be numbers");
  }
  return a + b;
}

try {
  let x = 10;
  let y = "5";
  console.log(addNumbers(x, y)); // This will throw an error
} catch (error) {
  console.error(error.message);
}

Output

Both arguments must be numbers

 

Usecase 2: Handling Different Types in Functions.

 

usecase2.js

function processInput(input) {
  if (typeof input === "string") {
    console.log("Processing string...");
  } else if (typeof input === "number") {
    console.log("Processing number...");
  } else if (typeof input === "boolean") {
    console.log("Processing boolean...");
  } else if (typeof input === "undefined") {
    console.log("Processing undefined...");
  } else if (typeof input === "object") {
    if (input === null) {
      console.log("Processing null...");
    } else if (Array.isArray(input)) {
      console.log("Processing array...");
    } else {
      console.log("Processing object...");
    }
  } else if (typeof input === "function") {
    console.log("Processing function...");
  } else if (typeof input === "symbol") {
    console.log("Processing symbol...");
  } else if (typeof input === "bigint") {
    console.log("Processing bigint...");
  } else {
    console.log("Unsupported type");
  }
}

// Test cases
processInput(42);                   // Output: Processing number...
processInput("Hello");              // Output: Processing string...
processInput(true);                 // Output: Processing boolean...
processInput(undefined);            // Output: Processing undefined...
processInput(null);                 // Output: Processing null...
processInput({ name: "Alice" });    // Output: Processing object...
processInput([1, 2, 3]);            // Output: Processing array...
processInput(function() {});        // Output: Processing function...
processInput(Symbol("unique"));     // Output: Processing symbol...
processInput(12345678901234567890n);// Output: Processing bigint...

Output

Processing number...
Processing string...
Processing boolean...
Processing undefined...
Processing null...
Processing object...
Processing array...
Processing function...
Processing symbol...
Processing bigint...


 

Previous                                                    Next                                                    Home