Search code examples
reactjsreact-routerdialogmaterial-uireact-link

Changing page address while closing dialog (material ui, react-router)


I am using the Material UI Dialog and react-router to create a sign-in option. Inside the sign-in dialog there is a sign-up link that is supposed to redirect the user to the sign-up page and close the dialog at the same time.

The code for the sign up link looks like this:

render() {
        return (
            <Link
                class="underline text-green-600 mx-1 cursor-pointer"
                to="/signup"
                onClick={this.props.handleClose}
            >
                Sign Up
            </Link>
        );
    }

Right now, when the Signup link is clicked the dialog closes without changing the page address. If the onClick command is removed the page address changes but the dialog is not closed. Is there a way to both close the dialog and redirect the page at the same time? Thank you


Solution

  • You can provide a function to react-router Link to prop:

    to: function
    A function to which current location is passed as an argument and which should return location representation as a string or as an object

    So one possible solution is:

      <Link
            class="underline text-green-600 mx-1 cursor-pointer"
            to={() => {
               const href = '/signup';
    
               this.props.handleClose();
    
               return href;
            }}
        >