I'm trying to use 2 different headers. I just need to save the current router page into a state. so I can implement conditional styling. something like this
const [page, setPage] = useState("black");
const data = {
page,
setPage,
};
// SOMETHING LIKE THIS BUT THIS DOESN'T WORK //
const ACTIVEPAGE: any = {
"/": setPage("black),
"/projects/project/[id]": setPage("black),
"/404": setPage("black),
"/booking": setPage("black),
"/teammembers": setPage("black),
"/projects": setPage("white),
"/singlecareers": setPage("white),
"/careers": setPage("white),
"/aboutus": setPage("white),
"/news": setPage("white),
"/news/[id]": setPage("white),
};
};
const router = useRouter();
return (
<MainContext.Provider value={data}>
<Header />
{children}
<Footer />
</MainContext.Provider>
);
};
export default Layout;
CodePudding user response:
you don't need to save current route in the state, you can make the condition on router.asPath
base like: router.asPath === "/404" ? "white" : "black"
also here you can see the example on this link, also as you can see the below code.
const childPaths = ["/", "/projects/project", "/404", "/teammembers"]
const router = useRouter();
return (
<MainContext.Provider value={data}>
<Header className={childPaths.includes(router.asPath) ? "black" : "white"} />
{children}
<Footer />
</MainContext.Provider>
);
};
export default Layout;
Or also you can do like this:
const ACTIVEPAGE = {
"/": "black",
"/projects/project": "white",
"/404": "white",
};
const router = useRouter();
// you can see the values on console
console.log("router.asPath", router.asPath)
console.log("ACTIVEPAGE[router.asPath]", ACTIVEPAGE[router.asPath])
return (
<MainContext.Provider value={data}>
<Header className={`${ACTIVEPAGE[router.asPath]}`} />
{children}
<Footer />
</MainContext.Provider>
);
};
let say this is you header component, you can do like this instead of passing props:
import { useRouter } from 'next/router'
import Logo1 from '../assets......';
import Logo2 from '../assets......';
const Header = () => {
const router = useRouter();
const childPaths = ["/", "/projects/project", "/404", "/teammembers"];
return (
<>
{childPaths.includes(router.asPath) ? <img src={Logo1} /> : <img src={Logo2} />}
</>
)
}
export default Header;
If you want to pass the props in header component you can do like this:
const childPaths = ["/", "/projects/project", "/404", "/teammembers"]
const router = useRouter();
return (
<MainContext.Provider value={data}>
<Header paths={childPaths} />
{children}
<Footer />
</MainContext.Provider>
);
};
export default Layout;
then you can get the props in header component, you can see the below code
import { useRouter } from 'next/router'
import Logo1 from '../assets......';
import Logo2 from '../assets......';
const Header = ({paths}) => {
const router = useRouter();
return (
<>
{paths.includes(router.asPath) ? <img src={Logo1} /> : <img src={Logo2} />}
</>
)
}
export default Header;