Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • DSA
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Go Premium
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App

Advanced ReactJS Guide Complete Reference

Last Updated : 27 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

ReactJS is a popular library for building modern user interfaces. While many developers are familiar with its basic concepts like components, state, and props, there are advanced features that can take your React apps to the next level. By exploring these features, you can optimize performance, manage complex states, and create more dynamic, efficient, and scalable applications.

Rendering and Re-rendering in React

In React, rendering and re-rendering are key concepts to understand, as they directly affect how efficiently your app updates and displays content.

Rendering in React

Rendering is the process where React takes the component's data (state and props) and turns it into a UI that the user can interact with. When a component is first loaded, React renders the component and displays it in the DOM.

JavaScript
import React from "react";

function MyComp() {
    return <h1>Hello, World!</h1>;
}

export default MyComponent;

In this code

  • React functional component called MyComponent.
  • It returns JSX that renders the text "Hello, World!" inside an <h1> element.
  • The component is exported using export default so it can be imported and used in other parts of the application.

Re-rendering in React

Re-rendering happens when the state or props of a component change. React will trigger a re-render to reflect the updated data in the UI. However, React optimizes this process to avoid unnecessary re-renders.

When Does Re-rendering Happen

  • Re-rendering occurs when: State changes: If the component’s internal state (useState, setState) changes, React will re-render the component to show the new state.
  • Props change: If the props passed to the component change, React re-renders that component to reflect the new props.

Real and Virtual DOM

Real DOM: The Real DOM is the actual representation of the UI in the browser. It’s a programming interface for web documents and represents the structure of a webpage as a tree of elements.

  • Slower Updates: When the state or data changes in a web application, the entire DOM may need to be updated.
  • Direct Manipulation: The Real DOM is updated directly. When a change is made, the browser updates the actual page, often causing reflows and repaints, which can be resource-intensive.
  • Heavy Operations: Modifying the Real DOM can trigger heavy operations like layout recalculations, which makes direct manipulation of the Real DOM inefficient, especially for large applications.

Virtual DOM: The Virtual DOM is a lightweight, in-memory representation of the Real DOM. It’s an abstraction that React uses to optimize the process of updating the UI. Rather than manipulating the Real DOM directly, React updates the Virtual DOM first and then compares it with the previous version to efficiently apply the minimal number of changes to the Real DOM. This process is called reconciliation.

  • Faster Updates: The Virtual DOM allows React to perform batch updates. It avoids direct manipulation of the Real DOM, making updates much faster.
  • Efficient Rendering: React uses a diffing algorithm to compare the Virtual DOM with the Real DOM and calculates the minimal set of changes needed to update the UI.
  • No Reflows or Repaints: By updating only what is necessary, React avoids reflows and repaints, which are costly operations in the Real DOM.

Higher-Order Components (HOCs)

Higher-Order Components (HOCs) are a powerful pattern in React. HOCs are functions that take a component and return a new component with additional props. They are typically used for cross-cutting concerns like authentication, logging, or data fetching, providing reusable functionality.

App.js
import React from 'react';
import DisplayMessage from './DisplayMessage';
import withLogging from './withLogging';

const EnhancedDisplayMessage = withLogging(DisplayMessage);

function App() {
  return (
    <div>
      <h1>React App with Higher-Order Component (HOC)</h1>
      <EnhancedDisplayMessage message="Hello, World!" />
    </div>
  );
}

export default App;
withLogging.js
import React from 'react';

function withLogging(WrappedComponent) {
    return function msg(props) {

        console.log('Rendering Enhanced Component with props:', props);

        // Render the wrapped component
        return <WrappedComponent {...props} />;
    };
}

export default withLogging;
DisplayMessage.js
import React from 'react';

function DisplayMessage({ message }) {
    return <h1>{message}</h1>;
}

export default DisplayMessage;

Output

hocc
Higher-Order Components

React Context API

The Context API allows you to share values between components without explicitly passing props down through every level of the tree. It is ideal for state that needs to be accessed by many components, such as themes or authentication status.

App.js
import React from 'react';
import MyContext from './MyContext';  // Import the created context
import ChildComponent from './ChildComponent';  // Import the child component

function App() {
    return (
        <MyContext.Provider value="Hello from Context!">
            <div>
                <h1>React Context API Example</h1>
                <ChildComponent />
            </div>
        </MyContext.Provider>
    );
}

export default App;
MyContext.js
import React from 'react';

// Create a Context with a default value
const MyContext = React.createContext('Default Value');

export default MyContext;
ChildComponent.js
import React, { useContext } from 'react';
import MyContext from './MyContext';

function ChildComponent() {
    const contextValue = useContext(MyContext);
    console.log('Context Value:', contextValue);
    return <p>{contextValue}</p>;
}

export default ChildComponent;

Output

context-1
React Context API

React Suspense and Lazy Loading

The React.lazy() function is used to dynamically import a component. This enables code splitting, where the components are loaded only when they are required.

  • React.lazy(): This is used to define the LazyComponent. It will only load the component when it is required (i.e., when it’s rendered).
const LazyComponent = lazy(() => import('./LazyComponent'));
  • Suspense: This is a wrapper around the lazy-loaded component. It displays a fallback (such as a loading spinner or a message) while the component is being loaded asynchronously.
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>

Performance Optimization in React

Optimizing the performance of a React application is crucial to ensure it runs smoothly, especially for larger applications with complex UIs and state management. Here are the key strategies and best practices for performance optimization in React:

1. Memoization of Components: React.memo(): React.memo() is a higher-order component (HOC) that helps to prevent unnecessary re-renders of a component. It wraps a component and only re-renders it if its props change.

Syntax

const MyComponent = React.memo(function MyComponent({ count }) {
console.log('Rendering MyComponent');
return <p>Count: {count}</p>;
});

2. Using useCallback for Memoizing Functions: The useCallback hook memoizes functions and ensures they are not re-created on every render. This is useful when passing functions as props to child components, especially when those functions are used inside a React.memo() wrapped component.

const increment = useCallback(() => setCount(count + 1), [count]);
return <ChildComponent increment={increment} />;
}

State Management with Redux

Redux is a predictable state container for JavaScript apps. It is ideal for managing the global state of the app. Redux allows you to centralize the state and dispatch actions to update the state.

Steps involved in Redux

  • Store: Holds the state.
  • Actions: Describe what happened.
  • Reducers: Specify how the state changes in response to actions.
App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment } from './actions';

const App = () => {
    const count = useSelector(state => state.count);  // Select only count
    const dispatch = useDispatch();

    return (
        <div>
            <h1>{count}</h1>
            <button onClick={() => dispatch(increment())}>Increment</button>
        </div>
    );
};

export default App;
actions.js
export const increment = () => ({
    type: 'INCREMENT',
});
  
reducers.js
const initialState = {
    count: 0,
    theme: 'light',
};

const counterReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return { ...state, count: state.count + 1 };
        case 'TOGGLE_THEME':
            return { ...state, theme: state.theme === 'light' ? 'dark' : 'light' };
        default:
            return state;
    }
};

export default counterReducer;
store.js
import { createStore } from 'redux';
import counterReducer from './reducer';

const store = createStore(counterReducer);

export default store;

Output

reduxxx
State Management with Redux

Error Boundaries

Error Boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the whole app.

App.js
import React from 'react';
import ErrorBoundary from './ErrorBoundary';
import BuggyComponent from './BuggyComponent';

function App() {
    return (
        <div>
            <h1>React Error Boundaries Example</h1>

            {/* Wrap BuggyComponent in ErrorBoundary */}
            <ErrorBoundary>
                <BuggyComponent />
            </ErrorBoundary>
        </div>
    );
}

export default App;
ErrorBoundary.js
import React, { Component } from 'react';

class ErrorBoundary extends Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false, errorMessage: '' };
    }

    static getDerivedStateFromError(error) {
        // Update state to show fallback UI
        return { hasError: true, errorMessage: error.message };
    }

    componentDidCatch(error, info) {
        // Log the error for debugging (optional)
        console.log('Error caught by ErrorBoundary:', error);
        console.log('Error information:', info);
    }

    render() {
        if (this.state.hasError) {
            // Fallback UI if there is an error
            return (
                <div>
                    <h1>Something went wrong:</h1>
                    <p>{this.state.errorMessage}</p>
                </div>
            );
        }

        return this.props.children;  // Render children if no error
    }
}

export default ErrorBoundary;
BuggyComponent.js
import React, { useState } from 'react';

function BuggyComponent() {
    const [count, setCount] = useState(0);

    if (count === 5) {
        // Simulate an error when count is 5
        throw new Error('I crashed!');
    }

    return (
        <div>
            <h1>Count: {count}</h1>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
}

export default BuggyComponent;

Output

error
Error Boundaries

Reconciliation Algorithm

The Reconciliation Algorithm in React is the process of comparing the new Virtual DOM with the previous one and determining the minimal set of changes required to update the Real DOM efficiently. This is important for React’s performance, as it allows React to make updates with minimal computational overhead, resulting in faster rendering.

How Reconciliation Works in React?

When the state or props of a React component change, React needs to update the UI. Here’s how the Reconciliation process works step-by-step:

  • Virtual DOM Creation: When a component is rendered, React first creates a Virtual DOM (an in-memory representation of the real DOM) to describe what the UI should look like.
  • Change in State/Props: When the state or props of a component change (e.g., through setState() or useState()), React triggers a re-render of that component.
  • New Virtual DOM Tree: React creates a new Virtual DOM based on the updated state or props. This tree represents the desired UI after the update.
  • Comparison (Diffing): React compares the new Virtual DOM tree with the previous one. This process is known as "diffing". React uses a series of heuristics to make this comparison more efficient.
  • Minimal Updates to Real DOM: After identifying the differences (or "diffs") between the old and new Virtual DOM, React applies the minimal set of changes to the Real DOM. These are the "patches" that update the actual page on the screen.

Server-Side Rendering (SSR) and Static Site Generation (SSG)

Server-Side Rendering (SSR) and Static Site Generation (SSG) are techniques that pre-render content on the server side to improve SEO and performance. React supports SSR with frameworks like Next.js, which provides an easy-to-use setup for building applications with SSR and SSG.

1. Server-Side Rendering (SSR):

Server-Side Rendering is a technique where the HTML for a page is generated on the server at the time the request is made by the user, rather than in the browser.

How SSR Works

  • When a user requests a page (for example, by visiting a URL), the server generates the HTML content for that page on the fly.
  • The server sends the fully rendered HTML to the browser, which then displays the content to the user.
  • Once the initial HTML is loaded, JavaScript runs on the client-side to make the page interactive (by attaching event listeners, fetching data, etc.).

2. Static Site Generation (SSG):

Static Site Generation is a technique where the HTML for a page is generated at build time instead of runtime. The pages are pre-rendered into static HTML files that are served to the user.

How SSG Works

  • During build time, all pages of the website are rendered into static HTML files.
  • These static files are saved and served by the server or CDN (Content Delivery Network) when requested by the user.
  • The user receives the static HTML immediately, and JavaScript is used for adding interactivity on the client side.

React Hooks: Advanced Usage

  • useReducer: Manage complex state logic in functional components.
  • useCallback & useMemo: Optimize performance by memoizing functions and values.
  • Custom Hooks: Reuse logic across components efficiently.

Conclusion

By mastering advanced React concepts like Higher-Order Components (HOCs), React Context API, React Suspense, and Redux, developers can build highly efficient, scalable, and maintainable applications. Understanding these patterns and optimization techniques will help you create faster, more user-friendly applications.

The Complete List of ReactJS Advanced Guides are listed below:

  • ReactCode-Splitting
  • React Context
  • React Fragments
  • React JSX In Depth
  • React refs
  • React Creating Refs
  • ReactJS Functional Components
  • ReactJS DOM
  • ReactJS Virtual DOM
  • React.js Uncontrolled Vs Controlled Inputs
  • Lifting State up in ReactJS
  • Optimizing Performance in ReactJS
  • ReactJS Reconciliation
  • What are error boundaries in ReactJS (16) ?
  • Lazy Loading in React and How to Implement it

K

kartik
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • ReactJS-Advanced

Similar Reads

    React Tutorial
    React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
    7 min read

    React Fundamentals

    React Introduction
    ReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
    6 min read
    React Environment Setup
    To run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
    3 min read
    React JS ReactDOM
    ReactDOM is a core React package that provides DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
    2 min read
    React JSX
    JSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, it’s actually a syntax extensi
    5 min read
    ReactJS Rendering Elements
    In this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
    3 min read
    React Lists
    In lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collections—like user profiles, product catalogs, or tasks—understanding how to work with lists.To render a
    4 min read
    React Forms
    In React, forms are used to take input from users, like text, numbers, or selections. They work just like HTML forms but are often controlled by React state so you can easily track and update the input values.Example:JavaScriptimport React, { useState } from 'react'; function MyForm() { const [name,
    4 min read
    ReactJS Keys
    A key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. When rendering a list, you need to assign a unique key prop to each element in th
    4 min read

    Components in React

    React Components
    In React, components are reusable, independent code blocks (A function or a class) that define the structure and behavior of the UI. They accept inputs (props or properties) and return elements that describe what should appear on the screen.Key Concepts of React Components:Each component handles its
    4 min read
    ReactJS Functional Components
    In ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Example:JavaScriptimport
    4 min read
    React Class Components
    Class components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
    3 min read
    ReactJS Pure Components
    ReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
    4 min read
    ReactJS Container and Presentational Pattern in Components
    In this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
    2 min read
    ReactJS PropTypes
    In ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
    5 min read
    React Lifecycle
    In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
    7 min read

    React Hooks

    React Hooks
    ReactJS Hooks, introduced in React 16.8, are among the most impactful updates to the library, with over 80% of modern React projects adopting them for state and lifecycle management. They let developers use state, side effects, and other React features without writing class components. Hooks streaml
    8 min read
    React useState Hook
    The useState hook is a function that allows you to add state to a functional component. It is an alternative to the useReducer hook that is preferred when we require the basic update. useState Hooks are used to add the state variables in the components. For using the useState hook we have to import
    5 min read
    ReactJS useEffect Hook
    The useEffect hook is one of the most commonly used hooks in ReactJS, used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.Fetchin
    5 min read

    Routing in React

    React Router
    React Router is a JavaScript library designed specifically for React to handle client-side routing. It maps specific URL paths to React components, allowing users to navigate between different pages or sections without refreshing the entire page.Types of React RoutersThere are three types of routers
    5 min read
    React JS Types of Routers
    When creating a React application, managing navigation between different views or pages is important. React Router is the standard library for routing in React, enabling seamless navigation while maintaining the Single Page Application (SPA) behaviour.What is React Router?React Router is a declarati
    10 min read

    Advanced React Concepts

    Lazy Loading in React and How to Implement it ?
    Lazy Loading in React is used to initially load and render limited data on the webpage. It helps to optimize the performance of React applications. The data is only rendered when visited or scrolled it can be images, scripts, etc. Lazy loading helps to load the web page quickly and presents the limi
    4 min read
    ReactJS Higher-Order Components
    Higher-order components (HOC) are an advanced technique in React that is used for reusing component logic. It is the function that takes the original component and returns the new enhanced component.It doesn’t modify the input component directly. Instead, they return a new component with enhanced be
    5 min read
    Code Splitting in React
    Code-Splitting is a feature supported by bundlers like Webpack, Rollup, and Browserify which can create multiple bundles that can be dynamically loaded at runtime.As websites grow larger and go deeper into components, it becomes heavier. This is especially the case when libraries from third parties
    4 min read

    React Projects

    Create ToDo App using ReactJS
    This to-do list allows users to add new tasks and delete them by clicking the corresponding button. The logic is handled by a click event handler whenever the user clicks on a task it gets deleted from the list.Lets have a quick look at what the final application will look like:ToDo App using ReactJ
    3 min read
    Create a Quiz App using ReactJS
    In this article, we will create a quiz application to learn the basics of ReactJS. We will be using class components to create the application with custom and bootstrap styling. The application will start with questions at first and then the score will be displayed at last. Initially, there are only
    4 min read
    Create a Coin Flipping App using ReactJS
    In this article, we will build a coin flipping application. In which the user can flip a coin and get a random result from head or tails. We create three components 'App' and 'FlipCoin' and 'Coin'. The app component renders a single FlipCoin component only. FlipCoin component contains all the behind
    3 min read
    How to create a Color-Box App using ReactJS?
    Basically we want to build an app that shows the number of boxes which has different colors assigned to each of them. Each time the app loads different random colors are assigned. when a user clicks any of the boxes, it changes its color to some different random color that does not equal to its prev
    4 min read
    Dice Rolling App using ReactJS
    This article will create a dice-rolling application that rolls two dice and displays a random number between 1 and 6 as we click the button both dice shake and generate a new number that shows on the upper face of the dice (in dotted form as a standard dice). The numbers on the upper face are genera
    4 min read
    Guess the number with React
    In this article, we will create the guess the number game. In which the computer will select a random number between 1 and 20 and the player will get unlimited chances to guess the number. If the player makes an incorrect guess, the player will be notified whether the guess is is higher or lower tha
    3 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • DSA Tutorial
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences