0

I want to programatically redirect the user to a loading page while I await for a response from the server api. I'm trying to do this inside a class component

The code I've got looks more or less like this:

class App extends Component { 
    constructor(props){
        super(props);
    }

    handleSubmit = () => {
      useNavigate("/loading")
      }
    }
    render() { 
      return ( 
        <div>
          <button onClick={this.handleSubmit}>
            Upload! 
          </button>
        </div>
      ); 
    } 
  }

export default App;

The thing is that nothing happens when i click the "Upload!" button. I've read that useNavigate cannot be used inside a class component but I'm not sure how I could implement this differently.

I guess my question is, how can I use useNavigate inside a class component?

EDIT: Thanks for your responses. I finally decided to convert my code to a function using these steps: https://nimblewebdeveloper.com/blog/convert-react-class-to-function-component

It now works like a charm.

rnavarro
  • 1
  • 1
  • 3

3 Answers3

0

Your clarification is correct, useNavigate() is a hook and therefore can only be used in a functional component. I'm thinking as an alternative you can wrap your App with withRouter, a HOC that gives the wrapping component access to the match, location, and history objects. From there, you can update the location with history.push('/loading').

Please see here for more information on history.

qslabs
  • 216
  • 2
  • 8
0

You cannot use useNavigate which is a react hook inside of class component.

you can by the way use react-router-dom which provide different way to manipulate browser url.

Yves Kipondo
  • 4,832
  • 1
  • 17
  • 26
0

Create a functional component as a Wrapper

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

export const withRouter = (ClassComponent) => {
    const RouterWrapper = (props) => {
        const navigate = useNavigate();

        return (
                <ClassComponent
                    navigate={navigate}
                    {...props}
                />
            );
        };

    return RouterWrapper;
};

Then in your App.js, export it by wraping with the functional component

import { withRouter } from './wrapper';

class App extends Component {
    constructor(props){
        super(props);
    }

    handleSubmit = () => {
        useNavigate("/loading")
    }

    render() { 
        return ( 
            <div>
                <button onClick={this.handleSubmit}>
                    Upload! 
                </button>
            </div>
        ); 
    } 
}

export default withRouter(App);
sid
  • 1,263
  • 6
  • 8