Why do I get this error when wanting to use router useNavigate

Viewed 4532

I learn React and can't understand how to fix this simple error:

I have a Codesandbox.

I have this code:

/* eslint-disable react/prefer-stateless-function */
import React from 'react';
import { useNavigate } from 'react-router-dom';
import AuthUserContext from './context';

const WithAuthorization = condition => Component => {
    class withAuthorization extends React.Component {
        doStuff = event => {
            const navigate = useNavigate();
            navigate('/', { replace: true });
        };

        render() {
            return (
                <AuthUserContext.Consumer>
                    {authUser => (condition(authUser) ? <Component {...this.props} /> : this.doStuff())}
                </AuthUserContext.Consumer>
            );
        }
    }

    return withAuthorization;
};

export default WithAuthorization;

It's not working this line is the reason const navigate = useNavigate(); and the error is this:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component

All I want is to navigate away when WithAuthorization detect a bad path.

Should I instead use maybe Redux to do this handling, it feels so ridiculous to send a Redux action?

1 Answers

The error is very self explain, you need to use the hook in function component and on the top level (you cant initilase it inside a function) so try this:

const WithAuthorization = condition => Component => {
 return props => {

    const navigate = useNavigate();

    const doStuff = event => navigate('/', { replace: true });
    
    return (
            <AuthUserContext.Consumer>
                {authUser => (condition(authUser) ? <Component {...props} /> : doStuff())}
            </AuthUserContext.Consumer>
          );
  } 
};
Related