TransWikia.com

How to get state variables from one component to another when i'm using history.push?

Stack Overflow Asked by Sai Sagar Seru on February 25, 2021

I am relatively new to React JS and have a question I have the following login form component

import React from "react"
import {
    Button,
    FormGroup,
    Label,
    Input,
    Form
} from "reactstrap";
import { withRouter } from "react-router-dom";
import axios from 'axios';

class Login extends React.Component {
    constructor(props){
        super(props);
        this.state={
            username:"Sai",
            password:"intelligencealliance",
            access_token:"" ,
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

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

    handleSubmit = event => {
        event.preventDefault();
        const headers = {
            'username': this.state.username, 
            'password': this.state.password
          }
        axios.post('/login', {} ,{ headers: headers })
          .then((response) => {
            this.setState({access_token : response.data.token})
            console.log(response.data);
            axios.get("/check_auth",{
              headers: {
                'access_token': this.state.access_token
              }
            })
            .then(auth => {
              console.log(auth)
              this.props.history.push('/dashboard');
            })
          }, (error) => {
            console.log(error.response.data.message);
          });
          
        
    }

    render()
    {   
        return(
            <div className="container">
              <Form onSubmit={this.handleSubmit}>
                  <FormGroup>
                  <Label for="username">Username</Label>
                  <Input type="username" id="username" value={this.state.username} onChange={this.handleChange}/>
                  </FormGroup>
                  <FormGroup>
                  <Label for="password">Password</Label>
                  <Input type="password" id="password" value={this.state.password} onChange={this.handleChange} />
                  </FormGroup>
                  <Button type="submit" value="submit" color="primary">Login</Button>
              </Form>
            </div>
        )
    }
}

export default withRouter(Login);

and the main component as follows

import React from "react"
import {
    
} from "reactstrap";
import { Switch, Route, Redirect } from "react-router-dom";
import Login from "./LoginComponent"
import Header from "./HeaderComponent";
import Footer from "./FooterComponent";
import Home from "./HomeComponent"
import Dashboard from "./DashboardComponent"

import "../App.css"
export default function Main() {
    
        return(
            <div>
                <Header />
                <Switch>
                    <Route exact path="/home" component={Home} />
                    <Route path="/login" component={Login} />
                    <Route path="/dashboard" component={Dashboard} />
                    <Redirect to="/home" />
                </Switch>
                <Footer />
            </div>
            
        )
    
}


What I want to do is get the username and password data from the login component to the dashboard component which is connected through '/dashboard' in route in the main component.

What is the best way to achieve this?

One Answer

In login page, you can pass params to dashboard page in this way.

this.props.history.push({
  pathname: '/dashboard',
  state: { 
    'username': this.state.username, 
    'password': this.state.password 
  }
});

You can access params on dashboard page like this:

this.props.location.state.username

this.props.location.state.password

Correct answer by Prime on February 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP