How to redirect to a route using onClick and React Router

Asked

Viewed 19,646 times

3

I have a screen (in React.js) called Cadastro.js. In it I have a form and the button register

By clicking this button, I wanted you to direct to the login screen, which is the Login.js.

How do I do that ?

Go on down mine index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Route, Link, BrowserRouter as Router } from 'react-router-dom'
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import Cadastro from './Cadastro';
import Contact from './Contact';
import Login from './Login';
import logo from './people.png'


const routing = (
<Router>
  <div>
      <ul>
          <li>
              <a href="logo"><img src={logo} alt="logo"/></a>
           </li>
           <li>
              <Link to="/">Home</Link>
           </li>
           <li>
              <Link to="/cadastro">Cadastro</Link>
           </li>
           <li>
              <Link to="/contact">Contato</Link>
           </li>
           <li>
              <Link to="/login">Login</Link>
           </li>
        </ul>


   <Route exact path="/" component={App}/>
   <Route path="/cadastro" component={Cadastro}/>
   <Route path="/contact" component={Contact}/>
   <Route path="/login" component={Login}/>
  </div>
</Router>
)

ReactDOM.render(routing, document.getElementById('root'));

My registration page:

import React, { Component } from 'react';
import './App.css';

class Cadastro extends Component {
  constructor(args){
    super(args)
    this.state = {

        firstName: '',
        lastName: '',
        gender:'',
        country:'',
        email: '',
        password:''   
    }
}

onChange(e){
  this.setState({
    [e.target.name]: e.target.value
  })
}
-------------------CRIEI ESSA FUNÇÃO MAS NÃO SEI COMO FUNCIONAR --------------
chamaLogin = () => {
  window.location.href ='/login.js'
 }


    render() {
    return(
        <div className="login-page">
        <div className="form">
          <form className="register-form">
          <h1>Cadastro</h1>

          <div className="firstName">
            <label htmlFor="firstName"> Nome </label>
            <input value={this.state.firstName} onChange={this.onChange.bind(this)} name="firstName" id="firstName" type="text"></input>
          </div>


          <div className="lastName">
            <label htmlFor="lastName"> Sobrenome </label>
            <input value={this.state.lastName} onChange={this.onChange.bind(this)} name="lastName" id="lastName" type="text"></input>
          </div>


          <div className="gender">
          <label htmlFor="gender"> Gênero </label>
          <select value={this.state.gender} onChange={this.onChange.bind(this)} name="gender" id="gender">
          <option value="">Selecione</option> 
           <option value="m">Masculino</option> 
           <option value="w">Feminino</option>  
           </select>
          </div>


        <div>
          <label htmlFor="country">Estado</label>
            <select value={this.state.country} onChange={this.onChange.bind(this)} id="country" name="country">
            <option value="">Selecione</option> 
            <option value="ac">Acre</option> 
            <option value="al">Alagoas</option> 
            <option value="am">Amazonas</option> 
            <option value="ap">Amapá</option> 
            <option value="ba">Bahia</option> 
            <option value="ce">Ceará</option> 
            <option value="df">Distrito Federal</option> 
            <option value="es">Espírito Santo</option> 
            <option value="go">Goiás</option> 
            <option value="ma">Maranhão</option> 
            <option value="mt">Mato Grosso</option> 
            <option value="ms">Mato Grosso do Sul</option> 
            <option value="mg">Minas Gerais</option> 
            <option value="pa">Pará</option> 
            <option value="pb">Paraíba</option> 
            <option value="pr">Paraná</option> 
            <option value="pe">Pernambuco</option> 
            <option value="pi">Piauí</option> 
            <option value="rj">Rio de Janeiro</option> 
            <option value="rn">Rio Grande do Norte</option> 
            <option value="ro">Rondônia</option> 
            <option value="rs">Rio Grande do Sul</option> 
            <option value="rr">Roraima</option> 
            <option value="sc">Santa Catarina</option> 
            <option value="se">Sergipe</option> 
            <option value="sp">São Paulo</option> 
            <option value="to">Tocantins</option> 
          </select>
        </div>


          <div className="email">
            <label htmlFor="email"> E-mail </label>
            <input value={this.state.email} onChange={this.onChange.bind(this)} name="email" id="email" type="email"></input>
          </div>


          <div className="password">
              <label htmlFor="password"> Senha </label>
              <input value={this.password} onChange={this.onChange.bind(this)} name="password" id="password" type="password"></input>
            </div>

----------------AQUI É ONDE NÃO SEI O QUE FAZER NO BOTÃO ------------------
          <div className="creatAccount">
            <button type="submit"
            onClick={() => chamaLogin()}
            >Cadastrar</button>
          </div>

        </form>
      </div>
      </div>
     )
   }
}

export default Cadastro;
  • Just a little comment window.location.href does not work in React because there is no route.

  • ah so it wouldn’t work anyway ... I thought it would work.

2 answers

5


As the most commonly used standard in Reactjs is to create Single Page Applications, you will need to use a library that creates the client(browser) side routes, as there is no server dictating the routes.

The most famous library is the React Router. See how to use here

Ex.:

import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

Import Cadastro from './cadastro'


function AppRouter() {
  return (
    <Router>
      <div>
        <Link to="/cadastro/" className="btn">Cadastre-se</Link>

        <Route path="/" exact component={Index} />
        <Route path="/cadastro/" component={Cadastro} />
      </div>
    </Router>
  );
}

export default AppRouter;

[UPDATE]:

To solve what you want using a function you will need to render the component <Redirect /> based on the state if the button was clicked.

How to do:

import React, { Component } from 'react';
import { Redirect } from 'react-router'
import './App.css';

class Cadastro extends Component {
  constructor(args){
    super(args)
    this.state = {
        firstName: '',
        lastName: '',
        gender:'',
        country:'',
        email: '',
        password:''
        redirect: false   
    }
}

onChange(e){
  this.setState({
    [e.target.name]: e.target.value
  })
}

chamaLogin = () => {
  this.setState({
    redirect: true
  })
 }
render() {

  if(this.state.redirect) {
    return <Redirect to="/login/" />
  }
  else {
    return (
      <div className="login-page">
      <div className="form">

         ... // Seu código de form atual. Removi só para simplificar.

          <div className="creatAccount">
            <button type="submit"
            onClick={() => chamaLogin()}
            >Cadastrar</button>
          </div>

        </form>
      </div>
      </div>
    )
  }
}

export default Cadastro;

  • Thank you for answering. I created the routes but only to click the fields of the sites and be redirected to your screen. Example : When you click on Home, you go to Home. When you click on Contact, you go to contact. However, I thought to call the screen on the button would be some javascript event. So it means I can route to that button ?

  • The simplest way to redirect is by using the tag Link and NavLink of the React-router that already does all the logic behind the cloths, as in the example above. Can you use this tag and just style with css to get the button style? @Verônicaemschermann.

  • I am new to reactJS, I am learning little by little...but not always in videos and articles I can find what I want. I am making a registration screen only, so that by clicking on the "sign up" button you go to the direct login page. I’m trying to write my code but it’s long kkkkkk`. I put my index.js (where the routes are) in my question.

  • I’ll create another answer showing you how to do it now that you’ve put the code

  • @Verônicaemschermann I believe the answer is now complete. I have made an update. You can check if this solves your problem?

  • Hi, sorry for the delay, I was unable to access this site...giving errors. So I did what you edited, but now you have an error asim = 'const' can only be used in a . ts file

  • I removed the const but it follows the same logic. @Verônicaemschermann

  • I removed it too but now it appears : . /src/Cadastro.js Line 108: 'chamaLogin' is not defined no-undef Line 117: 'Formcomp' is not defined no-undef

  • 1

    The answer code has been updated, now it is using another logic. You can test ?

  • of course!!! I will test, thank you for helping me...

  • THANK YOU! You saved my day, all that was missing was the "this.chamaLogin()" on the button. THANK YOU VERY MUCH <3 Have a good day

  • You’re welcome! @Verônicaemschermann. Mark the answer as resolved later :)

  • How do I do that ?

  • Check out this post: https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-reply

  • Ready!!! I think it was.

Show 10 more comments

2

Exchange the BrowserRouter for Router, uses a manual history, just to do that:

import { createBrowserHistory } from "history"
const history = createBrowserHistory({
  basename: "/"
})
window.redirect = history.push

now you can redirect from anywhere in your application

onClick() {
  redirect("/home")
}

To use the Router

function App() {
  return(
    <Router history={history}>
    ...a mesma coisa que o BrowserRouter, só muda a prop ali do history
  )
}
  • Hi, thank you for answering. I like the way you showed it. I have a question, I haven’t tried it yet, all this I write in index.js ? And the function I call on the screen I want ? That’s it ?

  • Yes, you put only once the history, but you must put push, thus: window.redirect = history.push, because the window is a global variable. If you are using SSR, just put global in place of window

  • Okay I did so : index.js I did as you directed (from createBrowserHistory import to window.redirect ....etc) On my login.js page I need to put a function on the link "Forgot your account? Sign up" , then I put something like : onClick() { redirect("/register") }. But is giving error " Line 72: 'redirect' is not defined no-undef "

  • This error is happening in your browser or linter ?

  • in the browser and visualCode terminal

  • The error is happening only in this part ?

  • Yes! only on the login.js page where I put the function. . /src/Login.js Line 71: 'redirect' is not defined no-undef Search for the Keywords to Learn more about each error.

  • 3 possibilities, 1) you have a variable that is named redirect on the page that is giving error, 2) createBrowserHistory is not creating history, something written wrong perhaps. 3) some application is using the same variable window.redirect and leaving her undefined, changes her name to redirect2 for example. Tries to debug and comes back with more details.

  • The first possibility = there is a <Redirect> this way of the React-router-gift, but I think it has nothing to do. The second possibility, here seems to be normal and the third possibility there is no way.

  • This only happens in your application. My last alternative would be to use window.redirect("/cadastro"), these are situations you will have to take a closer look at, it is specific to your PC. Tries to debug redirect in different files, methods, etc. See where it gets undefined then you will discover the root of the problem.

  • how weird...I still think it might be something I’m doing wrong. Complicated, but okay, thanks for all your help!

  • Go to the documentation of history and see if you’re really doing something wrong.

  • That’s right, I’ll check now!!! If it works out I’ll answer you here. Thanks again.

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.