Enter key for Route another page

I have a input for searchbox. I must make like; Write my words fors search then after i press enter it must need go another page with input value. So i can access that value with query string. So how can i route another page with value of input after i press enter ? Thank you for help! I Just add That codes for catch enter press.

 useEffect(() => {
    const listener = (event) => {
      if (event.code === "Enter" || event.code === "NumpadEnter") {
        alert("Enter key was pressed. Run your function.");
        event.preventDefault();
         
         
      }
    };
    document.addEventListener("keydown", listener);
    return () => {
      document.removeEventListener("keydown", listener);
    };
  }, []);

Answer

You don’t necessarily have to set an event listener, using onKeyDown event handler will also do. Enter key has a code of 13, so we just have to detect that.

Keep your value in a state (here, myValue), detect that you’ve pressed Enter key (here, using keyPressHandler method), and finally, pass the parameter to your route.

import {useHistory} from "react-router-dom"

function App() {
  let history = useHistory();

  const [myValue, setMyValue] = useState("");

  const handleChange = ({ target: { value } }) => {
    setMyValue(value);
  };

  const keyPressHandler = (e) => {
    if (e.which === 13) {
      // alert("You pressed enter!");
      history.push("/process/" + myValue);
    }
  };

  return (
    <div className="App">
      <input value={myValue} onKeyDown={keyPressHandler} onChange={handleChange} />
    </div>
  );
}

Working CodeSandbox Link