Sai Krishnadas
Sai Krishnadas

Reputation: 3409

React router isn't navigating

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

Upvotes: 2

Views: 68

Answers (2)

Shravan Dhar
Shravan Dhar

Reputation: 1560

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>

Upvotes: 3

Deep1man3
Deep1man3

Reputation: 192

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";

Upvotes: 3

Related Questions