Reactjs

For Beginners To Experts


Reactjs Basic

What is React

  • It is a JavaScript Library (not a framenwork) for creating interfaces (UIs).
  • It is used to make reusable UI components
  • It is created and maintained by Facebook that is based on components.
  • It is an open source declarative Javascript library.
  • We can make small UIs then combine all together to make a complex single interface(UI).
  • It create virtual DOM in memory which is a representation of the web browser's DOM.
  • It uses the virtual DOM which is faster than real DOM and makes the performance of our app higher.
  • It uses components and data pattern.
  • It was developed by Facebook in 2011.
  • Initial public release version is V0.3.0 was in May 2013.
  • Latest version is V18.0.0 that released in Aprill 2022.
  • It can be used on client and server-side.
  • It can be used for view layer of our app.
  • It was created by Jordan Walke a software engineer at Facebook company.
  • A ReactJS application is made up of many components
  • A React component responsible for displaying a small part of our app.
  • Small components can be nested or combined with other components to make a complex app.
  • React changes or updates what is to be updated, It is not updating the whole app that reduce the performance.
  • It changes a single DOM element instead of update or reload the whole DOM.
  • As an example, think of a webpage, the top navbar is a component, the left side bar is another component and the footer is the other components too. When we combined all three together it will create a webpage. All component are separate from each other and are reusable, any changes or any modifications to any of them, will update that component only which increase performance of our app.
  • React getting more popularity in the front-end, due to using features such as:
    High performance due to using virtual DOM built automatically in the memory than browsers' real DOM
    using JSX(JavaScript syntax extension which is an XML or HTML like syntax used by ReactJS for simplicity)
    Components (the functions in a separate file that do one job and are reusable)
    One-way Data Binding (data flows from parent to child - one way in Virtual DOM)
  • React is used only for the UI Layers of the app(view layers of the application).

Note:

What is declarative?

  • We tell React what to do, it will do it for us.
  • We do not need to tell the steps to do for us.
  • For example: We tell react to cook pasta for us, it will do it for us.
  • we do not need to tell the steps or instruction to make pasta for us.

Two ways to install React

  • Using command create-react-appto install necessary tools and modules automatically
  • Using Command npm to install packages and modules manually

First way of react installation using create-react-app

This command is a tool which install transpiling webpack and babel for us.

Babel transpiles ES6 to ES5 (jsx to javascript) to be readable by browsers.

JSX is JavaScript XML.

Install NodeJS and NPM platforms (package managers)

  • These package managers are necessary for developing ReactJS application.
  • Install NodeJS that comes with npm from nodejs.org.
  • First have a code editor such as visual studio code (vscode). You can download it from code.visualstudio.com
  • Create a folder on desktop.
  • Right click the folder open it with vscode
  • Open terminal in vscode by pressing shift+Ctrl+`on the keyboard.
  • Install React by type in the terminal the command npm install -g create-react-app (-g means install globally and installation must be in the root directory ie. main folder of react app we are making).
  • After installation of React , we can use create-react-app tool to create a React project. We name it first-app. Use the command create-react-app first-app in the terminal to create the React project with the name of first-app.
  • We can usenpx create-react-app first-app command to install React and React project at the same time. npx is a package runner tool that comes with npm 5.2 and above.

After the installation we have the following React structure folders

React Folders and Files Structure

node_modules folder
This directory or folder contains the whole React dependencies packages for building and running React project.
It includes React and other libraries such as third parties libraries. They are react , react-dom , dependencies of packages which are needed (transitive ones), such as ESLint, babal, webpack etc.

babel needed to convert JSX to JavaScript, ESlint for formating the codes and webpack for converting html and css with the help of a loader to modules.
webpack only knows about json and javascript files.
public folder
It holds all assets such as images, Javascript libraries and static files like index.html(mount the app by default) that we do not want to be processed by webpack.
src folder
It contains dynamic Javascript file that are needed to be processed by webpack.These files are:
The App.css, App.js, App.test.js, index.css, index.js, and serviceWorker.js.
.git folder
It includes information and history of the project.
The information includes repository address, commits, changes information for rolling back and so on.
By default is is hidden to prevent from deletion.
Some of folders and files in the .git folder are:
hooks: This folder includes script files that are executed before or after events.
objects: This folder display Git database object.
config: This file is local configuration file.
refs: This folder contains and keeps branches data and tags.
HEAD: This file keeps a reference to the current branch(by default to master branch) .
index: This file stores staging data (a binary file).
package.json:
It is a metadata for npm(package manager) to handle and configure project and its dependencies.
package-lock.json file
This file locks down the dependencies versions till the project always use the same versions.
When a package is installed, it is automatically created by npm.
It records the versions of all dependencies and its sub-dependencies when npm install any packages.
README.md file
This file includes basic information about the project such as:
It is a documentation about React
What the project is about.
Displaying the look of the project by an image.
Running and using instructions of the project.
Any other relevant information.
.gitignore file
This file allows Git to ignore some files like the following:
node_modules/ (big unnecessary files for Git server)
.cache/ (bundlers' temporary cache files)
dist/ (stores the build process output)
.env (it is a secure environmnet for values and variables that must not be shared)
.DS_Store (this file stores custom attributes of any visual information such as icon and so on)
coverage/ (it is a code coverage testing)
.vscode/ (stores project settings created by vscode - specific ones)

The src folder contains the following files.

App.css
This file styles the React App or the Components.
It is the first loaded root or top component that loads all other css files which is written in it.
App.js
This file is a container for all other components, combine all other components, it is as DOM Node or main page. It wrapes all other components
App.test.js
This file is used for mounting components to make sure that they didn't throw during rendering.
index.css
It will style the index.js file in the same directory or folder.
index.js
This file is the place where you mount(render) the whole react component (all components combined in this file) onto root element.
Index.js is the first file searched for in that directory, when adding an ES6 import statement.
logo.svg
It is the logo of react shown in web browser.
serviceWorker.js
This file is added to React build by default.
It is a script that runs in the browser's background, for usage of features that do not need users' interaction.

Run the app in browser by typing in terminal use the command npm start . It will show the default app we created in the browser on port 3000.

If you change the contents of the App.js file in the src folder, you will see the changes in browser on port 3000.

App.js is the root of our app that combine all components together. Then we connect App.js to index.js to show our app in the index.html file to view in browser.

To run the server in the browser by npm startcommand, we must be at the root folder I mean the main folder of our app. If not use the command cd first-app to go to root folder then type the command in terminal.

Second way of React installation using npm

To install packages and modules manually

  • Install nodejs that comes with npm packages from nodejs.org .
  • Create a folder on desktop name it reactApp
  • right click reactApp folder, open it with vs code.
  • Now we are in the root folder (reactApp)
  • Now in terminal type in npm -init -y to create a file named package.json for handling and creating any modules we are creating.
  • After creation of package.json, we create react and react Dom package by typing in terminal npm install react react-dom --save
  • We can install react and react-dom separately if you want. npm install react --save and npm install react-dom --save

Install Webpack

It is used for module packaging, development and production.

Webpack bundles webpack-dev-server for development, webpack for production and webpack CLI that contains necessary commands to be used in command prompt or terminal.

Use the command npm install webpack webpack-dev-server webpack-cli --save to install all three at one time

Instal Babel

babel is a JavaScript compiler that convert JSX into javascript to be readable by browsers.

  • To install Babel we have to have the following codes in terminal typed npm install babel-core babel-loader babel-preset-env babel-preset-react babel-webpack-plugin --save dev

    babel-loader is for jsx files, babel-preset-react is for updating browsers automatically and ES6 uses babel-preset-env

  • Then we add the following files in our folder.
  • index.html
  • App.js
  • index.js
  • webpack.config.js
  • .babelrc

webpack.config.js is used to configure webpack, it is the entry point of our app, it sets the development port, it adds plugins and loaders for different file types.

Add the following codes to configure webpack in webpack.config.json

  • Now in scripts object of package.json file replace the following codes.
  • Now add the following code in index.html file.

    Now we are importing the script source file of index_bundel.js into index.html file to Use fileHtmlWeb-packPlugin plugin from bundeled file which scale our app to be responsive to differnt devices.

    App.js

    It is entry point of our app to render our components

    Add the following code into App.js.

    Now we import App.jsfile (component) into root directory (index.js) file.

    Run the server and see the result by typing in terminal the command npm start

    Now you can create a bundled file named index_bundle.js which bundle all file into a file and merge them to have it with other files of webpage to load the app at once. For bundeling type the command npm run build in terminal to merge the file into one file (index_bundle.js).

    Note:

    • NPM is a package manager.
    • NPM starts the default server at localhost:3000in your browser.
    • 3000 is the port number.
    • Webpack, Babel and etc., are dependencies in React.
    • create-react-appis a tool that wrap all dependencies for react.
    • npm -v and nodejs -v will show the version number of package managers.
    • To use create-react-app we have to have Node version 8.10 and NPM version 5.6 and above.
    • Use cd + directory name to go to desired directory or folder.
    • DOM is a cross-platform dealing with HTML, XML or XHTML
    • The virtual Dom compare the previous and new changes in the DOM and then the Real DOM(browser's Dom) update only the changes, not the whole website or app. This makes the app faster.

    What is Difference between ReactJS and React Native?

    ReactJS: Focused on web development, ReactJS facilitates the creation and management of dynamic user interfaces for web pages and applications. It runs directly in web browsers, allowing developers to craft engaging and interactive UIs utilizing JavaScript.

    React Native is expressly crafted for the development of mobile applications, empowering the generation of native applications for mobile devices through the utilization of JavaScript and React. Its focus extends to mobile operating systems like iOS and Android, facilitating a cohesive codebase for both platforms.

    ReactJS ses CSS for styling, which can be applied through external stylesheets, inline styles, or CSS-in-JS libraries. React Native: Employs a styling system that resembles CSS but actually uses JavaScript objects to style components. This approach is more in line with how React itself handles UI logic.

    • React components are the building blocks of a user interface.
    • They are reusable and modular pieces of code.
    • They encapsulate specific function or UI(user interface) elements.
    • They break down UI into smaller, manageable parts.
    • They make our UI much more easier to develop,maintain, troubleshoot, and understand.

    There are two types of components in React:

    Functional Components:

    • Functional Components are simpler and stateless components that are essentially JavaScript functions.
    • They take in props as parameters and return React elements.
    • Functional components are used for UI elements when you don't need to manage state.

    Example 1: Using jsx (Javascript and XML)
    Functional Component without Props


    Example 2:
    Functional Component with Props


    Example 3:
    Functional Component with Destructuring Props


    Class Components:

    • React class components are ES6 classes that extend from React.Component.
    • They contain and control local state.
    • They are suitable for more complex components.
    • With the use of Hooks in React 16.8, functional components can manage state using the useState hook.

    Example 1:
    Class Component without State


    Example 2:
    Class Component with State


    Example 3:
    Class Component with Lifecycle Method


    Props:

    • Prop is short term for property.
    • They pass data from parent components to child components.
    • Props are read only, means the child components that are receiving props can not modify the value of it.

    Parent and child component are usually in separate .js or .jsx file

    Parent component or file collects all child components in one place or file.

    Each child components are written in a separate .js files


    Example 1:
    Functional Component without Props


    Example 2:
    Functional Component with Props


    Example 3:
    Class Component with Props and State


    States

    • State refers to a JavaScript object that depicts the present condition or data within a component.
    • state is confined within the component (internal) to the component and can be changed and modified (mutable) by the component itself (Unlike the props that could not be modified by child components).
    • State changes trigger re-rendering, and update data of that part or section of user interface (that components only).

    Example 1:
    Class Component with State



    Example 2:
    Functional Component with State using useState Hook


    Example 3:
    Class Component with Form Input and Controlled Component


    Handling Events

    • Handling events in React JS involves using event handlers to respond to user interactions, such as clicks, input changes, or mouse movements.
    • React provides a synthetic event system that wraps native browser events and normalizes them for consistent behavior across different browsers.
    • Understanding and mastering event handling is crucial for building interactive and dynamic user interfaces in React applications.

    Basic Event Handling:

    In JSX, you can specify event handlers by passing functions as props. Event names are written in camelCase, similar to their DOM counterparts.

    Example:

    Passing Arguments to Event Handlers:

    To pass extra data to an event handler, use arrow functions or the bind method to generate a new function.

    Example:

    Preventing Default Behavior:

    We can prevent the default behavior of an event using the preventDefault method available on the event object.

    Example:

    Event Propagation:

    React's event system also supports stopping event propagation using the stopPropagation method.

    Example:

    Using Synthetic Events:

    React provides synthetic events that are similar to native DOM events but with some differences. They are automatically cleaned up when the component is unmounted to avoid memory leaks.

    Example:

    In above example, event is a synthetic event object that wraps the native browser event.

    Conditional Event Handling:

    You can conditionally attach event handlers based on certain conditions.

    Example:

    In above example, event is a synthetic event object that wraps the native browser event.

    Conditional Rendering in React

    • In React, conditional rendering pertains to presenting various components or content depending on specific conditions.
    • conditional rendering enables the dynamic rendering of UI elements based on the application's state or user interactions.

    Conditional Rendering in JSX

    Using the if Statement:

    In JSX, we can use a standard JavaScriptif statement to conditionally render a component or content.

    Example:

    Using the ternary Operator:

    In JSX, we can use a ternary operator to conditionally render a component or content.

    This approach keeps the JSX code cleaner and more readable, especially for smaller conditional blocks.

    Syntax:

    Example:

    Using Logical && Operator:

    We can use the logicalAND (&&) operator to conditionally render elements based on a truthy value.

    This approach is concise and effective, especially when you only need to render a single component based on a condition.

    Example:

    Using Logical || Operator:

    We can use the logicalOR (||) operator to conditionally render elements based on a falsy value.

    This approach is concise and effective, especially when you only need to render a single component based on a condition.

    Example:

    Using Conditional Rendering with Inline Functions:

    This approach allows for more flexibility and enables you to nest conditional rendering within other JSX elements.

    We can use inline functions to conditionally render a component or content based on more complex conditions or logic.

    Example:

    Using Conditional Rendering with switch Statement:

    We can use the switch statement to conditionally render a component or content based on a value.

    For more complex scenarios with multiple conditions, use a switch statement inside the render() method.

    This approach is suitable when you have several different cases to handle, making the code more organized and readable.

    Example:

    Example:

    Explanation:

    We have a state variable isLoggedIn to track the user's authentication status.
    We conditionally render either the WelcomeMessage component if the user is logged in or the LoginForm component if the user is not logged in.
    When the user logs in successfully, the handleLogin function is called to update the isLoggedIn state, triggering a re-render to display the WelcomeMessage component.
    Conditional rendering in React provides a powerful mechanism for building dynamic and interactive user interfaces, allowing you to adapt the UI based on different application states and user interactions.

    Lists and keys in React:

    • In React, lists and keys are essential concepts for rendering dynamic content efficiently.
    • Lists allow you to render a collection of elements.
    • Keys help React identify which items have changed, been added, or been removed.

    Type of Lists and Keys:

    Basic Lists:

    Basic lists render a collection of items without needing to maintain state or handle complex logic.

    Example:

    Dynamic Lists with State:

    Dynamic lists use state to manage the collection of items, allowing for dynamic addition, removal, or modification of list items.

    Example:

    Lists with Unique Keys:

    Unique keys are identifiers assigned to individual items within a list, aiding React in recognizing items during the process of re-rendering

    Example:

    Note:

    • We use the map() function to iterate over each item in the list and render a corresponding JSX element.
    • Each list item have a unique key prop to help React efficiently update the DOM when the list changes.
    • In the case of dynamic lists with state, we use the useState hook to manage the list state and update it as needed.
    • When adding or removing items from a list, React utilizes keys to identify which items have undergone changes, additions, or deletions, thereby optimizing performance and preventing unnecessary re-renders.
    • With applying lists and keys in React, we can efficiently render dynamic content and build interactive user interfaces with ease.

    Forms In React:

    In React, forms are used to collect and process user input. There are several types of forms and various ways to handle form submission and input changes.

    Utilizing different types of forms in React will create powerful and interactive user interfaces for collecting user input and processing data.
    It is better to choose the right type of form that best fits the application's requirements.

    . Uncontrolled Forms:

    Uncontrolled forms allow the DOM to maintain the form data. You can still access form data using a ref, but React does not control the form data.

    Syntax:

    Controlled Forms:

    Controlled forms use React state to control the form data. Each form input element has an associated state value and an event handler to update that state value.

    Syntax:

    Formik Forms

    Formik is a library for building forms in React. It simplifies form management by handling form state, validation, and submission.

    Syntax:

    React Hook Form:

    React Hook Form is another library for building forms in React. It focuses on performance and flexibility by utilizing React hooks.

    Syntax:

    Example:

    10

    React Router

    • React Router is one of the most popular libraries for navigation purpose through pages.
    • It makes the navigation between different components without refreshing the page.
    • React Router create and manage routes in a React application that enables us to develop single-page applications (SPAs).

    Setting Up React Router

    First,create React application using Create React App as below.

    Then Install React Routeras below.

    Example

    Create a some simple components to navigate between.

    For instance, Home.js, About.js, and Contact.js.



    Then create an App.js component to have all the pages to be called in one place

    Note

    • React Router facilitates the rendering of distinct pages or components corresponding to specific URLs, effectively associating each component with a particular path.
    • "/" for Home
    • "/about" for About
    • "/contact" for Contact

    In App.js, the <Routes> component is used as a container for multiple <Route> components.

    Each <Route>defines a mapping between a path and a component.

    When the URL matches the path, React Router renders the specified component.


    . Nested Routes

    • Nested Routes are useful for creating layouts that persist across multiple pages, such as headers, footers, or sidebars.
    • With nested routes, you can have a parent route that renders a common layout component (<Layout>) and child routes that render components within that layout.
    • The <Outlet> component is where the nested routes are rendered.

    Example: A layout with nested routes

    Layout is always rendered, and depending on the URL, Home, About, or Contact is rendered within Layout.

    Nested Routes for layouts

    To create an applications that requires a consistent layout (e.g., shared headers or footers), nested routes allow you to define a common structure that wraps other views.

    Create a Layout component (Layout.js) that includes navigation links and an <Outlet> where child routes are rendered.

    In above we are incorporating the layout into routing by making it a parent route.

    In above approach keeps the navigation consistent across different pages, and enhancing the user experience.

    Example:

    An application with a nested structure: a main layout that contains a navbar, and two main sections, "Dashboard" and "Settings", each with their own sub-pages.

    Layout.js uses an Outlet to render either the "Dashboard" or "Settings" component, while Dashboard.js can further render nested components, such as specific views or widgets, into its own Outlet.


    Dynamic Routes

    Dynamic routes are essential for displaying information that depends on a parameter in the URL, like a specific blog post or product. With React Router.

    Define dynamic segments in the path by prefixing a segment of the path with : (colon).

    For instance, a route for individual blog posts might look like this:


    Protected Routes

    Protected routes are routes that require some form of authentication or authorization.

    To implement it, create a component that checks for user authentication and either renders the requested component or redirects to a login page.

    In below example demonstrates an authentication check.

    If auth.user is not present, it redirects to the /login page.

    Otherwise, it renders the children components, to access to the protected route.

    Example


    Redirecting in React

    Redirects will send users to a different page (The path that originally is not requested).

    For instance redirecting from old URLs to new ones or redirecting unauthenticated users away from protected routes.

    To implement a redirect in React Router,
    use the <Navigate> component with the replace prop to prevent the original route from being added to the history stack:

    Syntax

    In above syntax, it automatically redirect anyone who navigates to /old-path to /new-path instead.

    Note

    The Outlet and layout components in React Router are crucial for creating complex applications with nested routes

    The developer can build a consistent build a consistent structure across various pages.

    Outlet is a component provided by React Router that serves as a placeholder for rendering child routes.

    It is used within parent route components to specify where child routes should be rendered.

    This mechanism is particularly useful for creating nested routes.

    Example

    In your main application file (App.js)
    we define routes using Layout as a wrapper for other content.

    Example

    Note :Layout Components

    A layout component in React Router defines a structure that should be present across multiple routes.(A layout component in React Router is used to define a common structure (include headers, footers, sidebars, or any other persistent UI elements) that should be present across multiple routes.

    The layout component typically wraps the Outlet component till nested routes are rendered within the context of this structure.

    Hooks

    • In React, hooks refer to functions that enable the utilization of state and other React functionalities within functional components.
    • They provide a way to reuse stateful logic without changing the component hierarchy.

    Below are the primary categories of Hooks in React.

    State Hooks:

    Syntax:

    Example:

    Effect Hooks:

    • useEffect(): Allows performing side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM.

    Syntax:

    Example:

    Context Hooks:

    • useContext(): Allows passing data between components.
    • It Allows functional components to consume values from a context.

    Syntax:

    Example:

    Ref Hooks:

    • useRef(): Allows functional components to hold a mutable reference to a DOM node or a value.

    Syntax:

    Example:

    Reducer Hook:

    • useReducer(): An alternative to useState(), useful for managing more complex state logic.

    Syntax:

    Example: