skip to Main Content

In this code, I am trying to get the value of input and trying to redirect it to '/search/${searchvalue}' where 'searchvalue' is the value of the input. However whenever I try to do so, I get an error saying 'Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted'

"use client"
import { useState } from 'react';
import { useRouter } from 'next/router';
import Link from 'next/link';

export default function Navbar() {
  const [searchValue, setSearchValue] = useState('');
  const router = useRouter();

  const handleSearch = (e) => {
    e.preventDefault();
    router.push(`/search/${searchValue}`);
  };

  const handleInputChange = (e) => {
    setSearchValue(e.target.value);
  };

  return (
    <div id="navbarComp">
      <div id="navbar">
        <Link href="/">
          <div id="explore">
            <h1>Explore</h1>
          </div>
        </Link>
      </div>
      <div id="inputsearch">
        <form onSubmit={handleSearch}>
          <input
            className="dog"
            placeholder="Search"
            value={searchValue}
            onChange={handleInputChange}
          />
        </form>
      </div>
    </div>
  );
}

I tried multiple alternatives, none of which seemed to work.

2

Answers


  1. Chosen as BEST ANSWER

    Nevermind, I worked it out.

    Here is the working code

    "use client"
    import { useState } from 'react';
    import { useRouter } from 'next/navigation';
    import Link from 'next/link';
    
    export default function Navbar() {
      const [searchValue, setSearchValue] = useState('');
      const router = useRouter();
    
      const handleInputChange = (e) => {
        setSearchValue(e.target.value);
      };
    
      const handleSearch = (e) => {
        e.preventDefault();
        router.push(`/search/${searchValue}`);
      };
    
      return (
        <div id="navbarComp">
          <div id="navbar">
            <Link href="/">
              <div id="explore">
                <h1>Explore</h1>
              </div>
            </Link>
          </div>
          <div id="inputsearch">
            <form onSubmit={handleSearch}>
              <input
                className="dog"
                placeholder="Search"
                value={searchValue}
                onChange={handleInputChange}
                onSubmit={() => router.push(`/search/${searchValue}`)}
              />
            </form>
          </div>
        </div>
      );
    }
    

  2. try to pass the input event object to handleInputChange like:

    ...
    
    <input
     className="dog"
     placeholder="Search"
     value={searchValue}
     onChange={(e)=> handleInputChange(e)}
    />
    
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search