this solution works but I have more than one location. how can I add red color into different locations.
import { useRouter } from "next/router";
function Header() {
const router = useRouter();
return (
<>
<ul>
<li style={{ color : router.route == "/browse" ? "red" : "black" }}>Resut</li>
</ul>
</>
)
}
CodePudding user response:
Keep a static collection of red routes and use that in your check. For example
// route-styles.js
export const RED_ROUTES = new Set([
"/browse",
"/some-other-route",
// etc
]);
// Header.jsx
import { useRouter } from "next/router";
import { RED_ROUTES } from "./route-styles";
function Header() {
const router = useRouter();
return (
<ul>
<li
style={{
color : RED_ROUTES.has(router.route) ? "red" : "black"
}}
>Resut</li>
</ul>
);
}
Another option might be to create a map of routes to colour. That would let you use more than just the two choices
// route-styles.js
export const COLORS = {
"/browse": "red",
"/some-other-route": "red",
"/the-blue-one": "blue"
};
and in your component...
<li
style={{
color: COLORS[router.route] ?? "black"
}}
>
CodePudding user response:
Maybe a array would work?
import { useRouter } from "next/router";
import styled from "styled-components";
function Header() {
const router = useRouter();
const theRoutes = ["home", "browser", "view", "about"]
return (
<>
<ul>
{theRoutes.map(route =>
<li style={{ color: router.route === route ? "red" : "black" key={route}>{route}</li>
)}
</ul>
</>
)
}
CodePudding user response:
You could pass a prop to Header from page
export function Page () {
return (
<MainPage>
// if you have BaseLayout you have to pass it to Baselayout and from there to Header
// addiing only `red` prop will be evaluated red=True
<Header red />
<MainPage/>
)
}
In your Header
<li style={{ color : props.red ? "red" : "black" }}>Resut</li>