Switching from Page Router to App Router
Unanswered
Txie posted this in #help-forum
TxieOP
Hello, I have a component in Page Router that I use for the slug pages on my dashboard. When users switch the container they clicked on from the sidebar (Link Router switches between the slugs), the corresponding container becomes visible while the previously visible container becomes invisible. I am having issues trying to switch this component to App Router.
This is the code in my Page Router:
Component:
This is the code in my Page Router:
Component:
import React, { useState, useEffect } from "react";
import { useRouter } from "next/router";
const ContentWrapper = ({ parent, children, index, toggle }) => {
const [isActive, setIsActive] = useState(false);
const router = useRouter();
// Correctly access the first part of the slug array
// Check if `router.query.slug` exists and use the first value; otherwise, default to an empty string
const section = router.query.slug ? router.query.slug[index] : "";
useEffect(() => {
// Default to active state
let active = section === parent;
// If `toggle` is defined and is an array, iterate to determine active state
if (toggle && Array.isArray(toggle)) {
toggle.forEach((item) => {
// Check if the current route matches any toggle condition
if (
router.query.slug &&
router.query.slug[item.index] === item.section
) {
active = false; // Set active to false if any condition matches
}
});
}
setIsActive(active);
}, [section, parent, toggle, router.query.slug]); // Rerun this effect if `section` or `parent` changes
if (!isActive) {
return null;
}
return <>{children}</>;
};
export default ContentWrapper;1 Reply
TxieOP
The file structure where this code lies:
Other examples where
pages/client/dashboard/[...slug].js<div>
<ContentWrapper parent='home' index={0}>
<p>Home</p>
</ContentWrapper>
<ContentWrapper parent='tickets' index={0}>
<p>Tickets</p>
</ContentWrapper>
</div>Other examples where
toggle gets used:<>
<ContentWrapper parent={`${activeTicket}`} index={1}>
<div className='w-[63vw] h-[84vh] px-4'>
<OpenTicket ticket={ticket} />
</div>
</ContentWrapper>
<ContentWrapper
parent='ticket'
index={0}
toggle={[
{section: 'create-ticket', index: 1},
{section: `${activeTicket}`, index: 1}
]}
>
</ContentWrapper>
</>