Jayakarthik. jk
Jayakarthik. jk

Reputation: 103

How to use useNavigate( ) React-Router-Dom Hook in Class Component

How to use useNavigate( ) React-Router-Dom Hook in Class Component ?

export default class MovieForm extends Form {
  state = {
    data : {},
    error : {},
  }
  onSubmit(){
    // Navigate to Another Component
  }
  render(){
  // rendering the Form UI
  }
}

I want to Navigate to Another Component on Submitting the Form.

Official React-Router-Dom Documentation Says I can use 'useNavigate( )' Hook only inside a Functional Component.

I have a class Component and I can't make it functional Component. because It extends the Form Class and I want all the Functionality of Form Class in this MovieForm Component.

So how can I Navigate to Another Component.

Upvotes: 9

Views: 13012

Answers (2)

Mehrdad Moradi
Mehrdad Moradi

Reputation: 830

Since React router v6, you can use a Navigate component.

export default class MovieForm extends Form {
  state = {
    data : {},
    error : {},
    submitted : false,
  }
  onSubmit(){
    // Navigate to Another Component
    this.setState({submitted: true});
  }
  render(){
      // rendering the Form UI
      {submitted && 
        <Navigate to={// Router path to the target component} 
                  state={// you can pass state/props here}
        />
      }
  }
}

Upvotes: 4

Drew Reese
Drew Reese

Reputation: 203466

If you want to use the useNavigate hook then you have two choices basically.

  1. Convert class-based components into React function components and use the useNavigate hook.
  2. Create a custom withRouter Higher Order Component since react-router-dom@6 no longer exports one.

I won't cover the conversion case. Here's a withRouter HOC implementation.

Example:

import { useNavigate, /* other hooks */ } from 'react-router-dom'; 

const withRouter = WrappedComponent => props => {
  const navigate = useNavigate();
  // other hooks

  return (
    <WrappedComponent
      {...props}
      {...{ navigate, /* other hooks */ }}
    />
  );
};

export default withRouter;

Now you import withRouter and decorate the class component so that navigate and any other RRD hook values are injected as props.

...
import withRouter from '../path/to/withRouter';

class MovieForm extends React.Component { // *
  state = {
    data : {},
    error : {},
  }

  onSubmit() {
    const { navigate } = this.props;
    // Navigate to Another Component
    navigate("...target path...");
  }

  render() {
    // rendering the Form UI
  }
}

export default withRouter(MovieForm);

* React components should only extend React.Component, not other custom Javascript classes! See Composition vs Inheritance

Upvotes: 7

Related Questions