reactjsnext.jsnext-routernext-link

Page routing through dropdown (NEXT.js)


I want to route to different pages through dropdown selection. I'm new to react & next, and i have no idea how to do it.

"use client"

import Link from 'next/link';


function Home() {

  return (
    <main>
      <h1>Hello</h1>
      <select name="cars" id="cars">
        <option value="saab">Saab</option>
        <option value="volvo">
          <Link href='/volvo'>Volvo</Link>
        </option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
    </main>
  )
}

export default Home;

Whenever i select volvo, it should route to the volvo page.


Solution

  • What you're defining isn't something specific to Next.js or some error; do you know how events work? That’s basic JS. Because all you have to do is listen for the onChange event and redirect the user to the correct page.

    'use client';
    
    import { useRouter } from 'next/navigation';
    
    export default function Home() {
      const router = useRouter();
    
      return (
        <main>
          <h1>Hello</h1>
          <select
            onChange={(e) => {
              if (e.target.value === 'volvo') {
                router.push('/volvo');
              }
            }}
          >
            <option value='saab'>Saab</option>
            <option value='volvo'>Volvo</option>
            <option value='mercedes'>Mercedes</option>
            <option value='audi'>Audi</option>
          </select>
        </main>
      );
    }