admin管理员组文章数量:1404593
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>
);
};
本文标签: javascriptreactjs make component persist on specific routeStack Overflow
版权声明:本文标题:javascript - react.js make component persist on specific route - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744841234a2627934.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论