Home > OS >  Redirect from a Register Form with React Class in v6
Redirect from a Register Form with React Class in v6

Time:02-25

I'm doing a register form in React using a class and I would like to send the user to another page when the register is correct, the problem is that I haven't find any functional way to make it.

.then(data => {
            if(data.error != null) {
                console.log("Error => " data.error);
            } else {
                //Send the user to the login page
            }
        })

This is the part where I would send him to the login page, I have proved with 'useNavigation' and some more, but I can't find the correct way to get it.

CodePudding user response:

Since react-router-dom v6 supports only hooks. For implementing the navigate functionality inside a class-based component, you have to create a HOC and pass the hooks as props.

// withRouter.js

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

export const withRouter = (Component) => {
  const Wrapper = (props) => {
    const navigate = useNavigate();
    // any other hooks can be added and passed on
    return (
      <Component
        navigate={navigate}
        {...props}
        />
    );
  };
  
  return Wrapper;
};

then on your RegisterForm.jsx you can

import {withRouter} from './withRouter';

class RegisterForm extends React.Component{
//...

 yourFunction =() =>{

   .then(data => {
        if(data.error != null) {
           console.log("Error => " data.error);
         } else {
           //Send the user to the login page
           this.props.navigate('/loginPage'); 
         }
     })
 }
//...

}

export default withRouter(RegisterForm);

(https://github.com/remix-run/react-router/issues/7256)

  • Related