Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router v4 - How do you access the state that is passed via Redirect?

I am making a login page with the help of react that redirects to another page when the login is successful. Let me call the component that gets rendered when the login is successful 'A'. I want to pass data fetched from the database to component A and I am doing so by passing it in the 'state' attribute of the 'Redirect' component. However, I do not understand how to access this state in the 'Route' component that ultimately renders component A. Can anyone tell me how?

My code is as follows:

Login.js:

import React from 'react'
import Center from 'react-center'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import isEmpty from 'lodash/isEmpty'
import { browserHistory } from 'react-router'
import { Route, Redirect } from 'react-router-dom'

import Courses from '../pages/Courses'
import Logo from './shared/Logo'
import Routes from './Routes'
import Tiles from './Tiles'

export default class LoginForm extends React.Component
{
    constructor()
    {
        super()

        this.state = 
        {
            username: '',
            password: '',
            student: false,
            instructor: false,
            error_password: '',
            error_username: ''
        }

        this.onChange = this.onChange.bind(this)
        this.onSubmit = this.onSubmit.bind(this)
    }

    onChange(event)
    {
        this.setState({error_username:'', error_password:'', [event.target.name]: event.target.value})
        console.log(this.state)
        event.preventDefault()
    }

    onSubmit(event)
    {
        event.preventDefault()
        if (this.state.username && this.state.password)
        {
            this.props.loginRequest({username: this.state.username, password: this.state.password})
            .then(response => 
                {
                    this.setState(    // THE SERVER WILL SEND THE RELEVANT DATA HERE
                    {
                        username: '',
                        password: '',
                        student: response.data.student, 
                        error_username: response.data.error_username, 
                        error_password: response.data.error_password
                    })
                })
        }
        else
            this.setState({error_username: 'Please enter username', error_password: 'Please enter password.'})
    }

    render()
    {
        const styles =
        {
            buttonStyle:
            {
                margin: 'auto',
                width: '83'
            }
        }

        if (this.state.student)  ///  REDIRECT IS HAPPENING HERE
        {
            return (
            <Redirect to = {{
                pathname: '/loginS/student',
                state: { course_information }  /// HERE I WILL SEND THE RELEVANT INFORMATION THAT THE SERVER SENDS TO THE COMPONENT A 
            }}/> )
        }
        else if (this.state.instructor)
        {
            return <Redirect to = {'/loginI/instructor'} />
        }
        else 
        {
            // NOT RELEVANT
        }

        return(

            display 
        )
    }
}

LoginForm.propTypes = 
{
    loginRequest: PropTypes.func.isRequired
}

Routes.js

import React from 'react'
import { Switch, Route } from 'react-router-dom'

import Courses from '../pages/Courses'
import Login from './Login'
import Dashboard from './Dashboard'
import StudentsHandle from './StudentsHandle'
import CourseItem from './CourseItem'
import SemesterItem from './SemesterItem'
import Logo from './shared/Logo'
import Tiles from './Tiles'

export default class Routes extends React.Component
{
    render() 
    {
        return(
            <Switch>
                <Route exact path = '/' component = { Dashboard }/>
                <Route exact path = '/loginS' component = { Login } />
                <Route path = '/loginS/student' render = { (props) =>  < Tiles data = {this.props.coursesData} />} /> // HOW DO I ACCESS THE PROPS REDIRECT SENDS HERE?
                <Route path = '/instructor' component = { Courses } />
            </Switch>
        );
    }
} 
like image 285
eren555 Avatar asked Oct 22 '17 17:10

eren555


People also ask

How do I access router state in react?

Use the useLocation react-router hook to access the state present to the child component.

How do I get state value in react Dom router?

If you're using React hooks you can use useLocation hook. import { useLocation } from 'react-router-dom'; export const MyComponent = () => { const { state } = useLocation(); ... } Save this answer.

How do you pass additional data while redirecting to a route in react?

Using Link So when we click on the Register link, it will redirect to the /register route. But Link also allows us to pass additional data while redirecting. Here, at the place of data_you_need_to_pass , we can pass a string or object , array and so on and in the /register route we will get that data in props.

What are two ways of handling redirect with react router?

Two ways to handle redirecting on a user event such as create, update and delete with React Router.


3 Answers

You can use the location prop to access the state you have passed. Visit React-Router for reference. When you want to access that state, you can do it by this.props.location.state.

like image 180
Arslan Tariq Avatar answered Sep 22 '22 14:09

Arslan Tariq


If you're using React hooks you can use useLocation hook.

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

export const MyComponent = () => {
  const { state } = useLocation();

  ...
} 
like image 26
Ramon Balthazar Avatar answered Sep 18 '22 14:09

Ramon Balthazar


you can access state using this.props.location.state

like image 32
Codemaker Avatar answered Sep 21 '22 14:09

Codemaker