React Portal allows rendering child components into a DOM node outside the parent component's hierarchy. This is commonly used when child components need to be positioned outside the parent component's hierarchy, such as in modals or tooltips.
Using React Hooks in React Portal is identical to using them in standard components. Below, I'll demonstrate how to use React Hooks in React Portal by creating a simple modal component.
First, assume we have a modal root element in the HTML file:
html<!-- public/index.html --> <body> <div id="app"></div> <!-- Root node for React application --> <div id="modal-root"></div> <!-- Root node for Portal --> </body>
Next, we create a Modal component that uses useState and useEffect hooks, along with ReactDOM.createPortal to render content into modal-root:
jsximport React, { useState, useEffect } from 'react'; import ReactDOM from 'react-dom'; // Modal component const Modal = ({ children }) => { // Create a div element to render the modal content const [container] = useState(() => document.createElement('div')); useEffect(() => { const modalRoot = document.getElementById('modal-root'); modalRoot.appendChild(container); // Cleanup function when component unmounts return () => { modalRoot.removeChild(container); }; }, [container]); // The dependency array ensures the effect runs only when the component mounts and unmounts // Use React Portal to render children into a new DOM node return ReactDOM.createPortal( children, container ); }; // Using the Modal component const App = () => { const [modalVisible, setModalVisible] = useState(false); return ( <div> <button onClick={() => setModalVisible(true)}>Show modal</button> {modalVisible && ( <Modal> <div style={{ backgroundColor: 'white', padding: '20px' }}> <p>This is the content of the modal</p> <button onClick={() => setModalVisible(false)}>Close modal</button> </div> </Modal> )} </div> ); }; export default App;
In the above Modal component:
- Using
useState, acontainerDOM element is created, which remains unchanged throughout the component's lifecycle. useEffecthandles mounting and unmounting logic, ensuringcontaineris appended tomodal-rootand removed when the component unmounts.- The
ReactDOM.createPortalmethod renders the child elements of theModalcomponent intocontainer.
The App component includes a button to toggle the modal's visibility and a conditionally rendered Modal component, demonstrating how to implement a basic modal. In this example, useState is used to control the modal's visibility state.
This is how to use React Hooks in React Portal. You can use hooks such as useState, useEffect, useContext, and useReducer in the Portal just as you would in regular components.