Client component refresh
Unanswered
Persian posted this in #help-forum
PersianOP
I have a sidebar component which have a state that tells u which page you are in but when the user navigate to other page it refresh and the state return to the default page
how can i solve that?
how can i solve that?
17 Replies
Pacific herring
That normal
Dont useu useState for that
const pathname = usePathname();
// console.log(pathname) => "/" or "/search", "/shop", etc....Well now u can make condition with pathname
Because right now u have a state that is reset at each page change by /home, so the value will necessarily remain /home
import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p>
}@Pacific herring
import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p>
}
PersianOP
Okay what if i have other data that i want it to be the same when the page changes so what can i do ?
Pacific herring
u mean like /search/blablabla/blabla ?
@Dayo context?
PersianOP
what's that?
@Pacific herring u mean like /search/blablabla/blabla ?
PersianOP
sure
@Persian sure
Pacific herring
just use
pathname.startsWith('/shop')There is an example :
In this I got all possible route of my navigation bar
const routes = useMemo(() => [
{
icon: Compass,
label: 'Map',
active: pathname === '/',
href: '/',
},
{
icon: Rss,
label: 'Feed',
active: pathname.startsWith("/feed"),
href: '/feed',
},
{
icon: Search,
label: 'Recherche',
active: pathname.startsWith("/search") || pathname.startsWith("/movie"),
href: '/search',
}
], [pathname])In this I got all possible route of my navigation bar
And they are rendered like that :
{routes.map((item) => (
<Button variant={item.active ? "secondary" : "ghost"} className="w-full justify-start" asChild>
<Link href={item.href}>
<item.icon className="mr-2 h-4 w-4" />
{item.label}
</Link>
</Button>
))}Well for example with the
- /search/movie/details
- /search/artist
- /search/product/4684684568/info
....
Well the
/search pathname. If the pathname stars with /search its can be for example :- /search/movie/details
- /search/artist
- /search/product/4684684568/info
....
Well the
active property of the search gonna be true