TechnologyContext And Portals In React

Context And Portals In React

React is a popular open-source JavaScript library used to develop user interfaces, specifically web applications. With React, developers can create reusable user interface components that update and render the user interface efficiently. It has a component-based architecture, and the interface is segregated into small and self-contained components. React is simple and efficient; hence, it has become popular among web developers. 

Context and Portals in React are two important tools. Context allows us to share data between components without passing props through all the levels of the component tree. It is useful when we want to share data used by numerous components without passing props through each component.

Portals, on the other hand, give us a method of rendering the subtree of a React component outside of its parent component and outside the normal DOM hierarchy. They are useful when rendering a component at a different position in the DOM.

What is Context in React?

Context is a tool in React that every developer must be adept at. It enables us to pass down components from the parent to the child component. It’s done by saving props in a store. Context assists us in sharing data across components seamlessly. 

How to Use React Context?

Here is how you could use Context in React:

  • The first step is to create a new context. You could do this using the ‘createContext’ function present in the ‘react’ module.

import React from ‘react’;

const MyContext = React.createContext();

  • Wrap the ‘Provider’ component around the area of your component tree that requires access to Context’s data. 

<MyContext.Provider value={/* Your context data */}>

  {/* Your component tree */}

</MyContext.Provider>

  • To access the context data in your components, you can use the Consumer component or the useContext hook.

Using Consumer component:

<MyContext.Consumer>

{value => (

// Use the context value here

// Render your components

)}

</MyContext.Consumer>

Using useContext hook:

import React, { useContext } from ‘react’;

const MyComponent = () => {

const contextValue = useContext(MyContext);

// Use the context value here

// Render your components

};

Remember to import the context (MyContext in this example) into your component before using it.

Use Cases of Context in React

Here are some use cases of Context in React:

  • Accessibility: In React apps, Context is used to manage features related to accessibility. Information relating to high contrast mode or keyboard navigation is stored in Context. Components have easy access to this Context so that they can adapt to their behaviour and render content accordingly. 
  • Authentication of User: Context is used to manage user authentication. The Context saves information such as the username of the present user. Components that need access to user information can consume the user Context and conditionally render different content based on the user’s authentication status. 
  • Theme: Context is also used to pass down information about the theme to all the components in the application. It stores information such as fonts and colours, among others. Components can access the theme information and use the styles accordingly.

What is React Portal?

React Portal is a method that renders child components into DOM nodes beyond the component tree hierarchy’s parent DOM hierarchy. This feature was introduced in version 16.0 of React. A Portal is rendered outside of its parent DOM element but behaves in the application like any other React component. It has access to props and the context API. 

How to Use React Portals?

Here is an example of how you can use React Portals in your React application:

  • The first step is to import dependencies by typing out the following:

import ReactDOM from ‘react-dom’;

  • Make a container element in an HTML file where you want your portal content to be rendered. This container element will be outside the React component. Here is how you can do it:

<div id=”portal-container”></div>

  • Wrap your content in a portal using the ‘ReactDOM.createProtal()’ method. This method has two arguments: the target DOM element where you want to render it and the content to render. 

import React from ‘react’;

const MyComponent = () => {

  // Render the portal content using ReactDOM.createPortal()

  const portalContent = (

    <div>

      {/* Content to be rendered in the portal */}

      <h1>This is rendered in a portal!</h1>

    </div>

  );

  // Target the portal container element using its ID

  const portalContainer = document.getElementById(‘portal-container’);

  // Use ReactDOM.createPortal() to render the portal content into the target container

  return ReactDOM.createPortal(portalContent, portalContainer);

};

export default MyComponent;

Here, the content wrapped in the ‘<div>’ element will be rendered inside the ‘portal-container’ element beyond the normal component hierarchy.

  • Render the component normally in the root component.

import React from ‘react’;

import ReactDOM from ‘react-dom’;

import MyComponent from ‘./MyComponent’;

const App = () => {

  return (

    <div>

      <h1>My App</h1>

      <MyComponent /> {/* Render your component */}

    </div>

  );

};

ReactDOM.render(<App />, document.getElementById(‘root’));

Remember that the root element in your HTML file will be where the main component is rendered.  The portal’s content will be rendered within the ‘portal-container’ element, which again is outside the root component’s DOM hierarchy.

Use Cases of React Portals

As discussed earlier, React portals are useful when we want to render something in a separate part of the DOM tree that is distinct from the current position of the component tree. Here is how you could use React Portals:

  • Separate Component UIs: You can render a component distinct from its parent. Portals help you render such components in a separate part of the DOM while maintaining their position in the component tree of React.
  • Dropdown: Portals can render a dropdown menu that overlays other components or escapes container bounds at the top level of the DOM.
  • Integrate with Third-Party Libraries: You could use Portals to integrate third-party libraries that need components rendered at DOM locations. This helps seamlessly integrate external components with React applications.
  • Modals: The most common use of Portals are seen in modal windows. Modal components can be rendered at the highest level of DOM. This overlays other content and ensures they are seen on top of everything else in the app. 

Conclusion

React is rising in popularity and is used by most web developers for its simplicity, performance optimisation, and reusability. It is particularly popular in building mobile applications, large-scale web applications and single-page applications. Since web development is also gaining popularity with each passing day, programming enthusiasts can consider taking up full-stack development course. 

Online learning platforms like Eduonix have several courses designed for aspiring web developers. Eduonix guarantees not only top-notch faculty but also a 100% placement guarantee! Visit their website to know more. 

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -