React JS

Lord AbiollaLord Abiolla
24 min read
  1. What is React

React is a powerful, open-source JavaScript library for building user interfaces, primarily for single-page applications where you need fast and responsive UIs. Developed and maintained by Facebook and a community of individual developers and companies, React has become a cornerstone of modern web development. Its component-based architecture allows developers to create large web applications that can change data, without reloading the page.

A JavaScript library is a cluster of pre-written JavaScript code snippets that can be imported and used to perform common JavaScript functionalities easily. This promotes the re-usability of the code and hence faster development.

React enables developers create re-usable UI components which can then be used any number of times anywhere within the application, reducing time for debugging and re-writing.

React basically combines each small amounts of each of our HTML, CSS, and JS files into a single component so that each component has it’s own styling, functionality, etc and you can create as many components as possible, each working independently.

To get started with React, we need to understand JavaScript modules, which is our next topic.

  1. JavaScript Modules

JavaScript module is a file that allows you export its code to allow other JavaScript files to import and use the exported code as their dependencies.

Some of the popular module systems in JavaScript include:

  • Asynchronous Module Definition (AMD)

  • CommonJS Modules

  • Universal Module Definition (UMD)

  • ES Modules/JS modules/ ECMAScript modules

Amongst the module systems listed above, ES module is the official standard for JavaScript. The remaining three were created when JavaScript didn’t have a standardized module system and have since become part of JavaScript’s history.

For that reason, this article will focus mostly on ES module.

How to convert JavaScript file into a module

To convert a JavaScript file to an ES module, we do the following;

  1. Create a project directory: This is where the project’s HTML and JavaScript files will reside.

  2. Create your code files: Create the index.html, index.js, etc files.

  3. Add your JavaScript file to your HTML document: Open your index.html and insert your JavaScript file as shown below.

     <!DOCTYPE html>
     <html>
    
       <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>ES Module - CodeSweetly</title>
       </head>
    
       <body>
    
         <h1>ES Module Tutorial</h1>
         <!-- Add the "index.js" JavaScript file to this HTML document -->
         <script type="module" src="index.js"></script>
    
       </body>
    
     </html>
    

    In the HTML snippet, we have used <script>’s type=”module” attribute to convert the index.js JavaScript file to an ES module.

How to use an ES module

We can use ES modules as follows;

  1. Create a project directory: This is where our code files will live.

  2. Create your code files: Create code files inside the directory e.g., index.html, module-1.js, module-2.js

  3. Add the modules to your HTML file as shown below

     <!DOCTYPE html>
     <html>
    
       <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>ES Module - CodeSweetly</title>
       </head>
    
       <body>
         <h1>ES Module Tutorial</h1>
         <h2>Check the console</h2>
    
         <script type="module" src="module-1.js"></script>
         <script type="module" src="module-2.js"></script>
       </body>
    
     </html>
    

    In the HTML snippet, we’ve added two JavaScript files and used type=”module” attribute to convert them to ES module files.

    Note that JavaScript defers ES modules automatically, and therefore, you don’t need to use defer attribute in your module’s <script> element.

    Furthermore, if you open your app’s console, you get a CORS error because ES modules only work through http:// or https:// URLs and not locally via file:// URL. You can therefore load your HTML document using local server or using module bundler which we’re going to look at later.

How to export a module’s code

The two main ways to export a module’s item are;

  • Placing export keyword before your code.

  • Creating an export statement.

Placing export keyword before the code

For instance, if we open our module-1.js file and add the following;

// module-1.js

// Export the "bestClub" variable:
export const bestClub = "Your Club";

We prepended the const variable with the export keyword to tell the computer to share the bestClub variable with other modules that request it. The export keyword highlights the code you wish to share with other modules.

// Export the "multiply" function:
export function multiply(x, y) {
  return x * y;
}

The statement above instructs the computer to export multiply() to the modules that request it.

Creating an export statement

An alternate way to share a module's code is to use the export keyword as a standalone statement. You can do so by prepending a single export keyword to a block ({...}) of comma-separated names of code you wish to share.

For example;

// Create a variable named "bestClub":
const bestClub = "Your Club";

// Create a function named "multiply":
function multiply(x, y) {
  return x * y;
}

// Create an array named "fruits":
const fruits = ["Mango", "Apple", "Orange", "Lemon"];

// Export the three statements above:
export { bestClub, multiply, fruits };

Here, we’ve used an export statement to indicate that the computer can share bestClub, multiply, and fruits with other modules that request any of them.

Keep in mind that export works only as a top-level item. So, it would not work in a function.

How to import exported code

To import exported code, we use ES module’s import statement.

For instance, we can import bestClub from module-1.js into module-2.js as shown below.

// module-2.js

import { bestClub } from "./module-1.js";

From the snippet, we used import statement to bring in the bestClub variable from the module-1.js file. So, module-2.js is a top-level module because it contains another script, while module-1.js is a sub-module because it’s a script used inside another file.

Note:

  • import is used to import items from other modules

  • It’s mandatory to wrap the named export in curly braces while importing them.

  • import statement can only get another module’s code if exported with the export keyword. If you didn’t export the module’s code, import will throw an Uncaught SyntaxError

  • import keyword works only inside module, not inside regular JavaScript programs.

  • Imported module’s features are not available in the global scope. You can access imported items only in the script you have imported them into, not other places like JavaScript console.

  • Imported modules operate in strict mode by default regardless of whether you specified the strict statement.

Suppose we want to rename the code you’re exporting or importing, we can use the as keyword as shown in the example;

// module-1.js

// Create a variable named "bestClub":
const bestClub = "Your Club";

// Export the bestClub variable as "favoriteTeam":
export { bestClub as favoriteTeam };

Here we are instructing the computer to export bestClub variable as favoriteTeam and therefore, when importing the variable, we use the name favoriteTeam instead of bestClub.

// module-2.js

import { favoriteTeam } from "./module-1.js";

const myBestClub = favoriteTeam + " " + "is my best club.";

console.log(myBestClub);

We often rename module codes to prevent browsers from throwing errors due to name conflicts. Remember we can rename multiple exports by separating each as statement with a comma as shown below.

// module-1.js

const bestClub = "Your Club";
const fruits = ["Grape", "Apple", "Pineapple", "Lemon"];

function multiply(x, y) {
  return x * y;
}

// Export the three statements above:
export { 
  bestClub as favoriteTeam, 
  fruits as crops, 
  multiply as product 
};
// module-2.js

import { favoriteTeam, crops, product } from "./module-1.js";

const bestClub = `I bought ${product(2, 11)} ${crops[2]}s at ${favoriteTeam}.`;

console.log(bestClub);

Another cool trick is, what if we want to import all exportable items from a specific module without specifying each import’s name? In such case, we use import * as syntax to bring the items through a module object.

For example;

import * as allCountries from "./countries.js";

What is a default export? This is a technique developers use to export code anonymously (namelessly). You can implement default export by prepending the keyword default to the code you wish to export. This makes the computer share the code as a default export, i.e., the code gets exported with the special name default instead of it’s original name(if it had one).

For example;

// module-1.js

const bestClub = "Your Club";

// Export the bestClub variable as a default export:
export default bestClub;


OR

// module-1.js

// Export the string value as a default export:
export default "Your Club";

To import the default code, we use the default as syntax and specify the imported code’s name only as shown;

import { default as newName } from "./module-relative-path.js";

Module bundler

Module bundler is a tool developers use to bundle/wrap an app’s modules and dependencies into a single browser-compatible JavaScript file.

They allow browsers access the file you specified in the import statement. For instance. Suppose a browser runs a JavaScript file with a require(“./node_module/test/sample/app.js“) statement, the browser will throw an error that says Uncaught ReferenceError: require is not defined. This error is thrown because the browser can’t access files specified in a JavaScript program. However, we can use a module bundler to create a new JavaScript fie containing code browsers can read.

How does a module bundler work?

  1. It creates an output file in the project’s dist folder.

    • The bundler uses the output script file to save the bundled code.

    • The output file refers to the JavaScript file a bundler generates automatically for your project

    • Entry point is a file that the bundler uses to start building a dependency graph of all the project’s modules it need to combine into a single browser-compatible module. It’s the most critical file of a build step that links to every module in a project.

  2. The bundler compiles your code. The bundler checks build step’s entry point for any occurrences of import statements, and if it finds, it will combine the content of each dependency specified in the statements with the entry point’s content.

    • Build step is a process through which a module bundler builds a new browser compatible JavaScript file. The build step’s output file is sometimes called distribution code which’s the minified and optimized source code version.

    • A dependency is a file your script requires to work as intended. For example; in import { variable } from “./path/to/modue.js“, module.js is the dependency file because it’s a script the app depends on to function as designed.

  3. Finally, it saves the compiled code. The bundler will save the compiled code into output script file which will contain content of the entry point and its dependencies but no import statements.

Some most common examples of module bundler include;

  • webpack

  • browserify

  • rollup

  • parcel

How to use webpack

Here are the steps we can take to bundle our codes using webpack.

  1. Create your project directory where all your project files will live.

  2. At the project’s root folder, create a package.json file. This can be create using the command below

     // Using npm
     npm init -y
    
     // Using yarn
     yarn init -y
    

    The -y flag instructs npm or yarn to create a default package.json file. You must have node and npm installed in your system for the initialization above to work.

  3. Install the webpack module bundler. Running the below command installs webpack and webpack-cli as development dependency libraries.

     // Using npm
     npm install webpack webpack-cli --save-dev
    
     // Using yarn
     yarn add webpack webpack-cli --dev
    

    The webpack-cli package makes running webpack on the command line possible.

  4. Create your project’s directories. i.e., source code folder ./src and a distribution code folder ./dist

  5. Create your source code files i.e., index.html, index.js, etc. Note that webpack recommends saving source code in a ./src directory and distribution code on ./dist directory. Furthermore, webpack doesn’t alter code that don’t have import, export statements.

  6. Add the JavaScript file to your HTML document and remember, when using webpack, you don’t need to add type=”module” attribute to your <script> element.

  7. From here, you can install dependencies as shown below;

     // Dependencies needed in production
     npm install package-name --save
    
     // Dependencies needed in development
     npm install package-name --save-dev
    
  8. You can then import the dependencies installed and use them using the import keyword.

  9. You can create your bundle by running webpack like so:

     npx webpack
    

    This command will make webpack use your index.js as entry point, create a bundle (output file) in your project’s dist folder containing the content of the entry point and its dependencies.

    By default, webpack generates it’s main.js file which’s saved in the distribution folder.

    npx is node’s package runner that will automatically find and execute webpack.

  10. Now that we’ve created a browser-compatible bundle file, we need to tell the browser to use it instead of the index.js source code file. Therefore, we need to go to our HTML file and substitute the reference to our JavaScript source code with webpack’s distribution bundle.

    e.g., if our <script> had “./index.js“ in our HTML file, we replace it with “../dist/main.js“

Webpack can also allow you to use HtmlWebpacoPlugin to auto-generate and manage your project’s index.html file. To do so, we follow these steps.

// Install HtmlWebpackPlugin like so 
npm install html-webpack-plugin --save-dev

// Create a configuration file
touch webpack.config.js

// Add plugin to webpack's configuration
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    plugins: [new HtmlWebpackPlugin({
        template: "./src/index.html"
    })]
}

// Run the build step
npx webpack

The plugin will automatically insert the bundles that webpack generated into our HTML document, and with this we don’t need to include <script> tag in our HTML. We also initialized the template property with the path to our HTML source code, and therefore, npx webpack, HtmlWebpackPlugin will use ./src/index.html as a template to generate the new dist/index.html file.

Note: Whenever we make changes to our source code, we have to rerun the build step and refresh the browser. To automate the rerun process, we can add watch to the scripts fields in our package.json file as shown below.

{
  "name": "your_package",
  "version": "1.0.0",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --progress --watch"
  }
}

To invoke watch, we run npm run watch.

  1. Setting up a new React app

The development of React JS applications significantly benefits from the use of modules and module bundlers. To streamline the setup process and avoid manual installations of various packages, certain tools have been developed to aid developers in creating React applications more efficiently.

Some of the tools we need include the following:

  1. vite: This is a build tool that provides a straightforward approach to quickly set up new React.js projects. To ue it, we must ensure Node.js and Node package manager(npm) are installed on our computer.

    To verify if node and npm are installed, we can run the following commands in the terminal.

     // Check if node is installed
     node -V
    
     // Check if npm is installed
     npm -V
    

    If both results in an error, it means the software are not installed on your system. You can install node from official Node.js website.

  2. Package Manager: This is a tool that automates the process of installing, upgrading, configuring, and managing software libraries and dependencies. They manage the libraries our project depends on without needing manual downloads and installation. Most common package managers are:

    • npm: It’s integrated with Node.js and helps manage packages required for your project and it the largest software registry in the world.

    • Yarn: Developed by Facebook, it’s fast, reliable, and secure alternative to npm. It caches every package it downloads, so it never needs to download the same package again and parallelizes operations to maximize resource utilization.

  3. Create-React-App: This is also another tool you can use to create a React app. It is no longer recommended for use as it was deprecated. However, you may end up maintaining React applications that were created using create-react-app therefore it is important to know how to use it.

Creating React App with vite

Vite is a french word for fast and it’s a next-generation frontend build tool alternative to Create React App (CRA) but much faster.

Vite is a fast dev server (Hot module replacement), smaller, optimized build, easy configuration, and supports React, Vue, Svelte, etc.

To create a new React project, run the command below on the terminal within the directory you want to create your React app.

npm create vite@latest my-react-app -- --template react

Let me demystify the command:

  • npm → Node Package Manager

  • create vite@latest → downloads & runs the latest Vite project creator

  • my-react-app → name of your project folder

  • -- → tells npm “stop reading here, pass the rest to Vite”

  • --template react → sets up a React project (instead of vanilla JS or Vue, etc.)

After running the command, you should change directory into your react app directory, run npm install to install the necessary modules. After this, you’ll have a structure as shown below;

my-react-app/
├── node_modules/
├── public/
├── src/
│   ├── App.css
│   ├── App.jsx
│   ├── index.css
│   ├── main.jsx
│   └── assets/
├── .gitignore
├── index.html
├── package.json
├── vite.config.js
└── README.md

You need to run npm run dev and check your browser if your project is running well. You should see something like the image below:

How to Set Up a React App With Vite

  1. React Components

React components are building blocks of a React app.
Think of them like LEGO pieces, each piece can be small (like a button) or big (like an entire page), and you can reuse them anywhere.

In React, there are two main types of components you can use to build your UI: class components and functional components.

  • Class Components

Class components are defined using ES6 classes and they extend from React.Component or React.PureComponent. They can hold and manage local state and lifecycle methods, meaning, you can have more control over when your component renders and reacts to changes.

Class components are also verbose compared to functional components, requiring methods like render() for returning JSX.

NOTE: Class components are no longer commonly used. You are more likely to find them in legacy projects.

Example:

import { Component } from 'react';

class Welcome extends Component {
  render() {
    return <h1>Hello World</h1>;
  }
}
  • Functional Components

Functional components are simple JavaScript functions that can also be written as arrow functions.

Initially, they were stateless, but with the introduction of Hooks in React 16.8, functional components can now use state and other React features.

They’re also more concise and easier to read and test. They directly return JSX.

Example:

const Welcome = () => {
  return <h1>Hello World</h1>;
}

Component life-cycle

Component life-cycle refers to the various stages a component goes through from its mounting on the DOM (when it starts existing in the web page) to its unmounting (when it’s removed from the web page). Understanding these stages is crucial for managing components effectively, especially when dealing with external resources or subscriptions.

The lifecylce is categorized into three phases namely:

  • Mounting phase

This is when a component is created and inserted into the DOM.

Some of the methods used in this phase include:

  1. constructor(): This is used to initialize the state or bind event handlers. It’s called before a component is mounted.

  2. static getDerivedStateFromProps() :This is used to update the state based on props and its called right before rendering.

  3. render(): returns the JSX of the component. It’s the only method required in class component.

  4. componentDidMount(): Called after the component is mounted. Ideal for network requests, DOM interactions, and setting up subscriptions or timers.

  • Updating phase

This phase occurs when a component’s props or state changes, prompting a re-render. The methods here include:

  1. static getDerivedStateFromProps(): This is always called before every re-rendering.

  2. shouldComponentUpdate(): Determines whether a component should update, returning false prevents the re-render.

  3. render(): This is called again to re-render the UI.

  4. getSnapshotBeforeUpdate(): This is called right before the changes from the virtual DOM are to be reflected in the DOM.

  5. componentDidUpdate(): Used for DOM operations and network calls based on the new state, and is called after component updates.

  • Unmounting phase

This happens when the component is being removed from the DOM. The main method here is

  1. componentWillUnmount(): Which is called before the component is destroyed. It’s used to clean up any subscriptions, timers, or event listeners to prevent memory leaks.
  1. ReactDOM

The DOM(Document Object Model), is a programming interface for web documents that represents the page where programs can change the document structure, style, and content.

It represents the document as a tree of nodes and objects, with each node representing a part of the document such as an element, attribute, or text part.

For example;

When you load a web page in a browser, the HTML of the page is parsed and converted into a DOM. This then allows JavaScript to interact with the HTML and CSS of the page, JavaScript through the DOM can now add, remove, and modify elements on the page, change their styles, respond to event and more.

What then is ReactDOM?

ReactDOM is a package in React that provides DOM-specific methods to enable your React application to interact with the browser. It acts as a glue between the React library and the DOM.

What about Virtual DOM?

Virtual DOM is a lightweight copy of the actual web page structure (actual DOM), and it’s used in React. Meaning, instead of making changes directly to the real DOM which can be slow, React first changes the virtual DOM which later smartly updates only the parts of the actual web page that have changed. This method is faster and more efficient, making web pages react quicker to user interactions.

Differences between Real DOM and Virtual DOM

Real DOMVirtual DOM
It represents the actual structure of the web pageRepresents the virtual/in-memory representation of the web page.
DOM manipulation is expensiveDOM manipulation is very easy.
There is too much memory wastage.No memory wastage.
It updates slowly.It updates faster.
It can directly update the HTML.Cannot update the HTML directly.
Creates a new DOM if an element updates.Updates the JSX if an element updates.
It allows us to directly target any specific node (HTML element).Can produce about 200,000 virtual DOM nodes/second.
It represents the UI of your application.It’s only a virtual representation of the DOM.
  1. JSX

Traditionally,developers have separated markup and logic into separate files, using HTML for structure and CSS for styling and then writing JavaScript to handle interactions and data manipulation.

But what if there was a way to combine these technologies, simplifying the development process and making it easier to build complex user interfaces? That’s where JSX comes in.

JSX stands for JavaScript XML. It’s a syntax extension for JavaScript, used with React that allows you to write HTML-like code directly in your JavaScript files.

The syntax of JSX resembles HTML, with opening and closing tags, attributes, and nested elements. For example; To render a simple heading element, we can use this code:

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

The code looks like HTML, but it’s JavaScript. The element keyword creates a new variable named heading, and the value of that variable is the result of the JSX expression.

With JSX, you can embed HTML tags in your JavaScript code, and React will transform this JSX into regular JavaScript and HTML that browsers can understand.

Since browsers don’t understand JSX, the code is translated into JavaScript using Babel through transpilation. The browser can then execute the resulting JavaScript code.

For example;

The JSX code we previously wrote can be transformed into the one below;

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

JSX and React

JSX is a part of React which allow developers write the markup and logic of components in a singe file like in the example below;

import React from 'react';

function Greet() {
    return <h1> Hello world! </h1>
}

export default Greeting;

In the above example, we have a functional component called Greet which renders a h1 element with the greeting message.

The React compiler basically transforms the code into JavaScript code that can be executed by the browser, allowing components to be rendered on the screen.

The React compiler will transform Greet component into:

import React from 'react';

function Greet() {
    return React.createElement("h1", {}, "Hello world!")
}

Compilation happens behind the scenes however, the transformed code may be less readable than the original JSX code.

A new JSX transform feature was introduced in React 17 which imports special functions from React package’s new entry points allowing developers to use JSX without having to import React at the top of their files.

// Inserted by a compiler (don't import it yourself)
import {jsx as _jsx} from 'react/jsx-runtime';

function App() {
    return _jsx('h1', { children: 'Hello world' });
}

Using JavaScript expressions with JSX

JavaScript expressions can also be embedded directly within the markup to generate content dynamically, allowing developers to use JavaScript code to compute values, perform operations, and conditionally render content within their JSX components.

This can be demonstrated as shown below;

import React from 'react';

const MyComponent = () => {
    const name = 'Lord';
    const age = 24;

    return (
        <div>
            <h1> Hello, {name}! </h1>
            <p> You are {age} years old. </p>
            <p>
                Next year, you will be {age + 1} years old
            </p>
            {age >= 18 && <p> You are an adult.</p>}
        </div>
    );
};

export default MyComponent;

This example illustrates the use of JavaScript expressions like name, age, age + 1, and age >= 18 && <p> You are an adult.</p>, which are used to dynamically render content based on the values of name and age variables.

Using CSS with JSX

You can also apply CSS to JSX components through inline styles, separate CSS files, or CSS-in-JS libraries. Inline are defined directly within the JSX markup using JavaScript object, while separate CSS files or CSS-in-JS libraries allow for external and modular styling of components.

The example shows application of inline styles defined using JavaScript object.

import React from 'react';

const MyComponent = () => {
    const styles = {
        backgroundColor: 'blue',
        color: 'white',
        padding: '10px'
    };

    return (
        <div style={styles}>
            <h1> Hello, world </h1>
            <p> This is a component with inline style </p>
        </div>
    );
};

export default MyComponent;

Here, CSS properties like backgroundColor, color, and padding are set as key-value pairs in the styles object, and their values are strings representing the CSS values.

Important JSX rules

  1. Always return a single root element: Your JSX code must always be contained within a single outermost element(root element).

    For example;

     return (
         <div>
             <h1> Hello world! </h1>
             <p> This is my first React component </p>
         </div>
     );
    
  2. Use className instead of class: In HTML, we use class attribute to specify CSS class for an element. However, in JSX, we have to use className attribute instead.

    For example;

     // Good
     <div className="class-here"> CSS class element. </div>
    
     // Bad
     <div class="class-here"> CSS class element. </div>
    

    We use className in JSX because class is a reserved keyword in JavaScript and therefore to avoid conflicts, we don’t use it.

  3. Use curly braces for JavaScript expressions: When you need to include a JavaScript expression inside your JSX code, you need to wrap it in curly braces {}. This can be used for anything from displaying dynamic data to conditionally rendering components

  4. Use camelCase for most things in JSX: This convention is consistent with JavaScript naming conventions and helps maintain readability. e.g., use onClick instead of onclick, use className instead of class.

    For example;

     // Good
     <button onClick={handleClick} className="btn">Click me!</button>
    
     // Bad
     <button onclick={handle_click} class="btn">Click me!</button>
    
  5. Always close tags: Tags in JSX should always be closed even if they’re empty.

    For example;

     // Good
     <div></div>
    
     // Bad
     <div/>
    
  6. Use self-closing tags for empty elements: For empty elements, you can always use a self-closing tags.

    For example;

     // Good
     <img src="my-image.jpg" alt="My Image"/>
    
     // Bad
     <img src="my-image.jpg" alt="My Image"></img>
    

Importance of JSX in web development

  1. Allows developers build user interfaces in a more intuitive and familiar way.

  2. Instead of direct DOM manipulation, developers can use JSX to describe the structure of their user interface in a way that’s more like writing HTML.

  3. Allows for more efficient and flexible development since JSX is JavaScript, and developers can take advantage of features of JavaScript to create more complex, dynamic user interfaces.

  1. Props

Props, short for properties are like arguments you pass to a function. They are read-only values that are passed to a component, serving as a way to configure components, to make them reusable, and control the behavior of child components from parent components.

Think of props like a set of instructions given to a component that tel it how to behave or what kind of data it should display.

NOTE: Props are given to the component by it parent (the component that uses it), and they can’t be changed by the component that receives them.

For example:

Imagine you have a toy robot which you can tell what to say and what color to be. If you tell it “Say hello“, it says so, and if you tell it “Be red” it turns red. In React, the instruction is a prop.

Here is a code example;

function Robot(props) {
    return <h1> {props.mesasage} </h1>
}

Here, Robot is the toy robot while props.message is the instruction you give the robot.

To use the Robot;

function App() {
    return (
        <div>
            <Robot message="Hello, I am a robot!" />
            <Robot message="I like cookies" />
            <Robot message="Beep boop!" />
        </div>
    );
}

Here, each robot is the same toy, but you gave it different props (instructions).

We can also pass objects as props, allowing us to bundle multiple related pieces of data into a single prop.

For example;

// PrentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
    const user = {
        name: 'Lord',
        age: 24,
        occupation: 'Software Engineer'
    };

    return (
        <div>
            <h1> Welcome to our App </h1>
            <ChildComponent user={user} />
        </div>
    );
}

export default ParentComponent;
// ChildComponent.js

import React from 'react';

function ChildComponent(props) {
    return (
        <div>
            <p> Name: {props.name} </p>
            <p> Age: {props.age} </p>
            <p> Occupation: {props.occupation} </p>
        </div>
    );
}

export default ChildComponent;

In this example, we pass an entire user object to the ChildComponent. Inside ChildComponent, we access properties of the user object like name, age, and occupation.

Characteristics of props

  1. Immutability: Props are immutable, meaning they cannot be changed once they’re passed to a component. If a component want to modify the data, it should do so through its own state rather than modifying its props.

  2. Read-only: Components that receive props only know about their props and not how they were set or where they came from. This makes react components predictable and easier to debug.

  1. Conclusion

In conclusion, React applications are built using components that act as reusable building blocks and communicate through props to share data. These components are written in JSX, a syntax that blends JavaScript and HTML for easier UI creation, and are rendered to the browser using ReactDOM. Modern tools like Vite make setting up and running React projects faster by leveraging ES modules, which allow JavaScript code to be split into smaller, importable files for cleaner structure and better performance. Together, these concepts form the foundation of efficient, modular, and scalable React development.

10
Subscribe to my newsletter

Read articles from Lord Abiolla directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Lord Abiolla
Lord Abiolla

Passionate Software Developer with a strong enthusiasm for data, technology, and entrepreneurship to solve real-world problems. I enjoy building innovative digital solutions and currently exploring new advancements in data, and leveraging my skills to create impactful software solutions. Beyond coding, I have a keen interest in strategic thinking in business and meeting new people to exchange ideas and collaborate on exciting projects.