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>
);
};