Skip to content

Instantly share code, notes, and snippets.

@dsmabulage
Created September 25, 2023 05:01
Show Gist options
  • Save dsmabulage/b29aa2055e19d67652a329d99b635c73 to your computer and use it in GitHub Desktop.
Save dsmabulage/b29aa2055e19d67652a329d99b635c73 to your computer and use it in GitHub Desktop.
Query Param Search
'use client';
import { FC, useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
const colorVariants = [
{
name: 'black',
label: 'Black',
},
{
name: 'blue',
label: 'Blue',
},
{
name: 'red',
label: 'Red',
},
];
const Home = () => {
const router = useRouter();
const searchParams = useSearchParams();
const color = searchParams.get('color') ?? 'black';
useEffect(() => {
router.replace(`?color=${color}`, {
scroll: false,
});
}, [router, color]);
return (
<div className='text-center pt-4'>
{colorVariants.map((variant) => (
<Link
key={variant.name}
href={`?${new URLSearchParams({
color: variant.name,
})}`}
className={`bg-gray-100 py-2 px-4 rounded-full border-2 ${
color === variant.name ? 'border-blue-500' : 'border-gray-200'
}`}
>
{variant.label}
</Link>
))}
</div>
);
};
export default Home;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment