javascriptreactjsreact-hooksreact-router

How can I import useNavigate in a handler file?


I have a separate file with all my functions but when I try to import my library react-router-dom and use useNavigate I get errors like

Uncaught TypeError: Cannot read properties of null (reading 'useContext')

or

Uncaught (in promise) Error: Minified React error #321;

Code:

import {useNavigate} from 'react-router-dom';

const navigate = useNavigate();

const onSubmit = async () => {
  navigate('/success');
};

export default {onSubmit};

I tried to declare the variable inside the function but I got error

import {useNavigate} from 'react-router-dom';

    const onSubmit = async () => {

     const navigate = useNavigate();

      navigate('/success');
    };

Solution

  • You cannot use use hooks outside components. https://reactjs.org/docs/hooks-rules.html

    Instead, you can create useOnSubmit hook which you can then use in component body if you want

    const useOnSubmit = (cb = () => {}) => {
       const navigate = useNavigate(); 
    
       const onSubmit = async () => {
          await cb();
          navigate('/success');
       }
       
       return onSubmit;
    }
    

    Now you can use this hook like the following

    const SampleComponent = () => {
       const onSubmit = useOnSubmit(() => {
          // do submit logic here
       });
    
       return <button onClick={onSubmit}>Submit</button>
    }