-1

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.

Rayaan R
  • 33
  • 5

1 Answers1

1

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>
  );
}
onlit
  • 728
  • 5
  • 19
  • Thanks for the help mate, and found that the new useRouter hook should be imported from next/navigation and not next/router. https://stackoverflow.com/a/74493127/19512950 Appritiate your help. – Rayaan R Jun 26 '23 at 18:37
  • Wow! They changed lots of things. I'm sticking with the pages dir for my projects. The app dir is very new and unstable for a production-ready app – onlit Jun 26 '23 at 23:20