skip to Main Content

Good morning,

I just posted my question here because I can’t find any answer anywhere… I’m simply trying to create a redirection with the "redirect" function of "react-router-dom" but it is completely ignored and I don’t understand why …

Imported function:

{ redirect } from "react-router-dom";

My function:

switchView = () => {
    this.setState((state, props) => {
        const url = state.signup === true ? '/signin' : '/signup';
        redirect(url);
        return {
            signup: !state.signup
        };
    });
}

My implementation:

<Button variant="contained" color="secondary" size="small" fullWidth={true} onClick={this.switchView}>
    {this.state.signup ? 'Connexion' : 'Inscription'}
</Button>

I redid the entire road management part…

Unfortunately I can’t go through the useHistory hook because I’m going through a Component class extension. I don’t know if you have a solution for this?

Do you have an idea ?

Thanking you.

2

Answers


  1. use withRoute hoc for class components and access history object through props

    Login or Signup to reply.
  2. If you are working with a class component and need to perform redirection using React Router, you can access the history object by wrapping your component with the withRouter higher-order component (HOC) from "react-router-dom."

    import React from 'react';
    import { withRouter } from 'react-router-dom';
    
    class YourComponent extends React.Component {
      switchView = () => {
        const { history } = this.props;
        const url = this.state.signup ? '/signin' : '/signup';
        history.push(url);
        this.setState((state) => ({
          signup: !state.signup,
        }));
      };
    
      // Rest of your component code
    
      render() {
        return (
          <Button
            variant="contained"
            color="secondary"
            size="small"
            fullWidth={true}
            onClick={this.switchView}
          >
            {this.state.signup ? 'Connexion' : 'Inscription'}
          </Button>
        );
      }
    }
    
    export default withRouter(YourComponent);
    

    This HOC injects the history prop into your component, allowing you to access the history object and perform the redirection.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search