0

Hey all I'm new to React and having an issue using react-router-dom v6 useNavigate hook. I'm trying to add onClick functionality to buttons to change the path using navigate but anytime I click my button this error comes up Uncaught TypeError: navigate is not a function. This is my simplified code if anyone can help.

Nav.js

const Nav = () => {
  const { navigate } = useNavigate();
  const itemsList = [
    { text: "Home", icon: <InboxIcon />, onClick: () => navigate("/") },
    { text: "Contact", icon: <MailIcon />, onClick: () => navigate("/contact") },
    { text: "About", icon: <InboxIcon />, onClick: () => navigate("/about") },
  ];
  return (
   <List>
      {itemsList.map((item, index) => {
        const { text, icon, onClick } = item;
          return (
           <ListItem button key={text} onClick={onClick}>
             {icon && <ListItemIcon>{icon}</ListItemIcon>}
               <ListItemText primary={text} />
             </ListItem>
            );
          })
   </List>

App.js

function App() {
  return (
    <div className="App">
      <Nav />
      <Routes>
        <Route exact path="/" element={<Main />} />
        <Route exact path="/contact" element={<contact/>} />
        <Route exact path="/about" element={<about/>} />
      </Routes>
    </div>
  );
}

index.js

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);
dizzleduff
  • 13
  • 4
  • 1
    You have a typo. `const { navigate } = useNavigate` should be `const navigate = useNavigate` https://reach.tech/router/api/useNavigate – evolutionxbox Feb 22 '22 at 14:02
  • Ahh, so I can't use brackets around variable names. Thank you very much! – dizzleduff Feb 22 '22 at 14:05
  • 1
    Brackets around variable names means something specific. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – evolutionxbox Feb 22 '22 at 14:06

0 Answers0