1

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
  • 11
  • 1
  • 4

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
  • 406
  • 4
  • 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
  • 5,289
  • 1
  • 18
  • 31
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,779
  • 8
  • 10
  • "withRouter" can be used when React version is below or 16.x. And "useNavigate" can be sued with Function component only as its hook. What to do for React 18.x and class component? – maulik Aug 04 '22 at 11:24