最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - react.js make component persist on specific route - Stack Overflow

programmeradmin3浏览0评论

I am rendering a component like this in Approuter.js on element document.getElementById("side-bar"); , element is in wordpress homepage

When I click and route to /deals , the component renders but disappears right away in 1 sec . How do I modify it so the component Sidebar stays/persist as long as user is on /deals

note: DealsList renders correctly and persist when routed to /deals

  import React, { useEffect, useState } from "react";
import { Routes, Route, useLocation } from "react-router-dom";
import { createPortal } from "react-dom";  
...

export const AppRouter = () => {
    const location = useLocation();
    const [categories, setCategories] = useState({});
    const [sidebarContainer, setSidebarContainer] = useState(null);

    useEffect(() => {
        // Fetch categories once when the app loads
        fetchCategories().then((data) => {
            if (typeof data === "object" && data !== null) {
                setCategories(data);
            } else {
                console.error("Invalid category format:", data);
                setCategories({});
            }
        });
    }, []);

    useEffect(() => {

        // Find the sidebar container from the WordPress PHP homepage

        const container = document.getElementById("side-bar");
        setSidebarContainer(container);
    }, []); // Run once on mount

    return (
        <div className="app-wrapper">
            <Header />

            <div className="content-wrapper">
                <div className="page-container">
                    <main className="main-content">
                        <Routes>
                            <Route
                                path="/"
                                element={
                                    <>
                                    ...
                                    </>
                                }
                            />
                            ..
                            <Route path="/deals" element={<DealsList />} />
                        </Routes>
                    </main>
                </div>

                {/*  Inject Sidebar into WordPress' existing #side-bar */}
                {location.pathname === "/deals" && sidebarContainer
                    ? createPortal(<Sidebar categories={categories} />, sidebarContainer)
                    : null}
            </div>

            <Footer />
        </div>
    );
};
发布评论

评论列表(0)

  1. 暂无评论