Home > Mobile >  useNavigate() breaks the hook
useNavigate() breaks the hook

Time:12-05

I made a simple react hook.

import React from "react";
import { useNavigate } from "react-router-dom";

export default function SearchReq(searchTerm: string) {
  if (searchTerm === "") return;
  const navigate = useNavigate();
  console.log(searchTerm);
  // window.location.href = "/search?searchTerm="   searchTerm;
  navigate("/search?searchTerm="   searchTerm, { replace: true });
}

But for some reason it is giving me an error I had figured out that the line that is causing an error is const navigate = useNavigate() but I don't understand why can any one explain it to me?

Here is the error: enter image description here

CodePudding user response:

to use the useNavigate hook, you need to make sure that your React component is rendered inside a Router component from the react-router library.

import React from "react";
import { useNavigate } from "react-router-dom";
import { Router } from "react-router"; 

function MyComponent() {
  const navigate = useNavigate();

  const handleClick = () => {
    navigate("/some/other/route");
  };

  return (
    <button onClick={handleClick}>
      Go to some other route
    </button>
  );
}

function App() {
  return (
    <Router>
      <MyComponent />
    </Router>
  );
}

Requested Edit :

import React from "react";
import { useNavigate } from "react-router-dom";

function MyComponent() {
  const navigate = useNavigate();

  // Navigate to a different route when the button is clicked
  const handleClick = () => {
    navigate("/some/other/route");
  };

  return (
    <button onClick={handleClick}>
      Go to some other route
    </button>
  );
}

CodePudding user response:

Define the hooks in root level of the component. before return statement

export default function SearchReq(searchTerm: string) {

  const navigate = useNavigate();  

  // window.location.href = "/search?searchTerm="   searchTerm;

  useEffect(() => {
        if(searchTerm)  navigate("/search?searchTerm="   searchTerm, { replace: true });

  }, [searchTerm])

  return null
}
  • Related