-1

I am new in react.js. How to do redirect in react.js after login ? Is it different from Vue.js routing ? I installed this package. I read this question. I tried in different ways but no one is working.

Could you please help me with some basic code or any basic tutorial ?

Here is my code

import React, { Component } from 'react';
import Auth from '../services/Auth'
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory, Redirect } from 'react-router-dom'

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {email: '',password:''};

        this.handleChange = this.handleChange.bind(this);
        this.handleClick = this.handleClick.bind(this);
    }
    handleChange (event){
        this.setState({[event.target.name]: event.target.value});
    }
    handleClick(){
        var data = {
            client_id: 2,
            client_secret: 'ispGH4SmkEeV4i5Tz9NoI0RSzid5mciG5ecw011f',
            grant_type: 'password',
            username: this.state.email,
            password: this.state.password
        }

        fetch('http://127.0.0.1:8000/oauth/token', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then((response) => response.json())
        .then((responseData) => {

            Auth.setToken(responseData.access_token,responseData.expires_in+ Date.now());

            this.props.history.push("/dashboard");  

        })
    }
}

export default Login;

I am getting error like below

enter image description here

abu abu
  • 6,599
  • 19
  • 74
  • 131

4 Answers4

2

There are two way of redirect in React.js.

One is using redirect from react-router-dom.

And other is using third-party library i.e. history (this is what you're using) If you're not getting history in your prop then you need to use withRouter.

example:

    import {
  withRouter
} from 'react-router-dom'

    class Login extends React.Component {
      handleSubmit = (user) => {
        saveUser(user).then(() =>
          this.props.history.push('/dashboard')
        ))
      }
      render() {
        return (
          <div>
            <h1>Register</h1>
            <Form onSubmit={this.handleSubmit} />
          </div>
        )
      }
    }

    export default withRouter(Login)

For details, refer:

How to redirect in react.js with example

1

Could you please show the errors?

The component seems incomplete to me.

If you are using react-router v4, the component should be wrapped with the withRouter. This passes the history prop to the component. Can you please confirm if the history prop is not undefined?

Apologies if I misunderstood your question.

Shishir Anshuman
  • 1,115
  • 7
  • 23
  • Thanks @Shishir. I updated the question. That will be helpful for you. Thanks. – abu abu Apr 23 '18 at 13:40
  • Yep. Wrapping the component with the withRouter will solve the issue. If It didn't, please let me know, I'll create an example for you to understand the flow. – Shishir Anshuman Apr 23 '18 at 13:51
  • Thanks @Shishir. How can I do that ? – abu abu Apr 23 '18 at 14:15
  • 1
    @abuabu I have created an example that shows how the react-router works. https://codesandbox.io/s/qlmrxorl66 Feel free to play around with it. Also, I would recommend going through the [official docs](https://reacttraining.com/react-router/web/guides/quick-start). And please mark it as the answer if I answered your question correctly. :) – Shishir Anshuman Apr 23 '18 at 14:34
0

First of all, you need to wrap your app ( basically, app ) with BrowserRouter. Then you need to define Route for your component.

<Route to='/dashboard' component={dashboard} {...this.props} />

the error you get is because you don't pass the props properly.

Kyaw Siesein
  • 705
  • 8
  • 14
0

try this:

import React, { Component } from 'react';
import Auth from '../services/Auth'
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory, Redirect } from 'react-router-dom'

class Login extends Component {
    constructor (props) {
        super(props);
        this.state = {email: '',password:''};

        this.handleChange = this.handleChange.bind(this);
        //this.handleClick = this.handleClick.bind(this);
    }

    handleChange (event) {
        this.setState({[event.target.name]: event.target.value});
    }

    handleClick = (event) => {
        var data = {
            client_id: 2,
            client_secret: 'ispGH4SmkEeV4i5Tz9NoI0RSzid5mciG5ecw011f',
            grant_type: 'password',
            username: this.state.email,
            password: this.state.password
        }

        fetch('http://127.0.0.1:8000/oauth/token', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then((response) => response.json())
        .then((responseData) => {

            Auth.setToken(responseData.access_token,responseData.expires_in+ Date.now());

            this.props.history.push("/dashboard");  

        })
    }
}

export default Login;

The difference is an array based function:

handleClick = (event) => {}

become:

handleClick (){}
Shah Alom
  • 1,031
  • 1
  • 14
  • 26