"use client" import { createPortal } from "react-dom"; import { useEffect, useState }…
- User
"use client"
import { createPortal } from "react-dom"; import { useEffect, useState } from "react";
const UnderHeader = ({ children }: { children: React.ReactNode }) => { const [mounted, setMounted] = useState(false);
useEffect(() => { const timeout = setTimeout(() => { setMounted(true); }, 1000); // задержка для демонстрации, уберите в реальной реализации return () => clearTimeout(timeout); }, []); return ( createPortal( <div style={{ minHeight: '200px' }}> {mounted ? children : <SkeletonPlaceholder />} </div>, document.getElementById("under-header") as HTMLElement ) );};
const SkeletonPlaceholder = () => { return ( <div style={{ height: "100%", background: "#eee", display: "flex", justifyContent: "center", alignItems: "center" }}> Loading... ); };
export default UnderHeader;
- Assistant
This React component,
UnderHeader, utilizes React Portals to render its content outside of the DOM hierarchy of the parent component's subtree. Here's a breakdown of how it works:-
State Management: The component uses the
useStatehook to declare amountedstate variable, which initially is set tofalse. This variable is used to track if the content should be displayed or if a loading placeholder should be shown. -
Effect Hook: The
useEffecthook is used to update themountedstate after a delay of 1 second. This delay is achieved using the function. The timeout simulates a loading period and is cleared when the component unmounts to prevent memory leaks.
-
- User
Error: Target container is not a DOM element.
- Assistant
The error message "Target container is not a DOM element" indicates that the
createPortalfunction is trying to render content to a DOM element that does not exist or hasn't been correctly identified. This typically happens if the element with the specifiedidis missing or not available when the portal is created. Here's how you can diagnose and fix the issue: - User
Can u send me the correct code?
- Assistant
Certainly! Below is a revised version of the
UnderHeadercomponent with added error handling to ensure the target element exists before attempting to create a portal. I've also included comments to guide you through the changes: