2

I have a signIn and signUp in the nav bar.

My "/" path renders SignUp component and the SignUp component has a form with input and button.

On sumbitting the form or clicking the button I should be taken to ("/signin") SignIn page which renders my signIn component.

But, my issue is once i click button or sumbit the form it still stays in the ("/") signUp page and doesn't navigate to signIn page ("/signin")

Code :

import { Redirect } from "react-router-dom";

function Signup() {
  const handleClick = () => {
    <Redirect to="/signin" />;
  };
  return (
    <div>
      <form>
        <label>
          Enter Mobile Number
        </label>
        <input />
        <button onClick={handleClick} >
          Get OTP
        </button>
      </form>
    </div>
  );
}

export default Signup;

App.js

function App() {
  return (
    <Router>
      <div>
        <Nav />
        <Switch>
          <Route exact path="/" component={Signup} />
          <Route path="/signin" component={SignIn} />
        </Switch>
      </div>
    </Router>
  );
}

Things I tried to fix this,

I wrapped in button :

<button onClick={handleClick} >
<Link to="/signin"> Get OTP </Link>
</button>

I also tried onSumbit in form instead of onClick

2 Answers 2

3

One way is to compose in a Link element like:

import { Link } from "react-router-dom";
<Link to='/'>
  <button>
     Redirect to home
  </button>
</Link>

And for form, you can do like:

import { history } from "react-router-dom";
<form onSubmit={() => history.push("/")}>
...
</form>
Sign up to request clarification or add additional context in comments.

Comments

3

You need to wrap the button in Link:

<Link to='/'>
  <button>
     Redirect to home
  </button>
</Link>

and add Link component from 'react-router-dom':

import { Link } from "react-router-dom";

5 Comments

Thanks, This works ! I will accept this answer. And what if i need to use the onSubmit on form instead of onClick of button? Wraping the whole form doesn't work i guess
In this case you can use history.push(path);
Using <Redirect /> works in that case ? @guilhermevictorramalhonatal
Yes works. but you will need a conditional to fire the redirect.
Quickly scribbled Redirect from home page to dashboard page: link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.