reactjsreact-hooksreact-router-dom

Unable to navigate to another web page using useNavigate in my ReactJS app


I am trying to navigate to a different web page using 'useNavigate'. I am getting the error message below and I don't quite understand what I am doing incorrectly. Please can someone advise?

import React from 'react';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';
import { useNavigate } from 'react-router-dom';

import SendIcon from '@mui/icons-material/Send';

const Header = () => {

  const SendMessage = () => {
  console.log('Send message!');
  const navigate = useNavigate();
  navigate('/writeMessage');

}
 return (
<Box sx={{ flexGrow: 1 }}>
  <AppBar position="static">
    <Toolbar>
      <IconButton
        size="large"
        edge="start"
        color="inherit"
        aria-label="menu"
        sx={{ mr: 2 }}
      >
        <MenuIcon />
      </IconButton>
      <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
        MyApp
      </Typography>
        <SendIcon sx={{ marginRight: "20px" }} onClick={SendMessage}> 
        </ SendIcon>
      <Button variant="contained" >Connect Wallet</Button>
    </Toolbar>
  </AppBar>
</Box>
);
}

export default Header;

Console:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Solution

  • You are calling the useNavigate hook in a nested function. This breaks one of the Rules of Hooks, "Don’t call Hooks inside loops, conditions, or nested functions."

    Move it to the component scope.

    const Header = () => {
      const navigate = useNavigate();
    
      const SendMessage = () => {
        console.log('Send message!');
        navigate('/writeMessage');
      };
    
      ...