1

I want to open a new page(component to which I have made a route) on click of a button and pass some data to it.
Till now I have done this:
In my app.js component I have this (routes):

class App extends Component {
  render() {
    return (
      <Router>
       <div>
        <Route exact path="/" component={Login} />
        <Route exact path="/dashboard" component={Dashboard} />
       </div>
      </Router>
    );
  }           

In Login component I have:

class Login extends Component {
  constructor(props){
    super(props);
    //this.state = {isToggleOn: true};
    this.loadDashboard = this.loadDashboard.bind(this);
    this.handleOnSubmit = this.handleOnSubmit.bind(this);
    this.setData = this.setData.bind(this);
    this.state = {values:null}
  }
  setData(data){
    this.setState({values:data});
  }
  loadDashboard(token){
    console.log(token);
    axios({                 //this function is used to fetch some data from server
      method:'get',
      url:'http://localhost:3000/api/dashboard',
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
     .then(function (response) {
       console.log(response.data);     //it works!   
       this.setData(response.data)
     })
     .catch(function (error) {
       console.log("Error in loading Dashboard "+error);
     });
  }
render() {
    return (
      <div>
         Username: <input type="email" name="fname" /><br />
         Password: <input type="password" name="lname" /><br />
         <button onClick={this.handleOnSubmit}>LOG IN</button>
         <Dashboard data={this.state.values} />
      </div>
    );
  }
} 

NOTE response.data contains an array of three json objects.
Till now I am unable to print the passed value using my child component(Dashboard).
My Dashboard component looks like this:

class Dashboard extends Component {
  constructor(props){
    super(props);
      console.log(this.props.data);
  }
  render() {
    return (
      <h2>hi{this.props.data}</h2>     <!--Only hi gets printed -->
    );
  }
}

export default Dashboard;         
  • How to on click of a button only display Dashboard component ie change my url to /dashboard and pass some values to it?
Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318
noobie
  • 691
  • 1
  • 10
  • 32
  • You would navigate away from the page using dynamic routing and pass the information with it, See this answer on how do pass information to the component to which you have navigated dynamically https://stackoverflow.com/questions/44121069/how-to-pass-parameters-with-history-push-in-react-router-v4/45263164#45263164 and see this question on how do you dynamically route, https://stackoverflow.com/questions/44127739/programatically-navigate-using-react-router/44128108#44128108 – Shubham Khatri Sep 12 '17 at 05:44
  • @ShubhamKhatri how to pass parameters while calling another component using a button?? – noobie Sep 12 '17 at 05:56
  • You will not to calling another component, rather routing to the component, so on press of button you are calling a handleSubmit function, it is in this function that you need to do dynamic routing and pass the params to history.push. Please read the answers on the two questions I mentioned in my above comment – Shubham Khatri Sep 12 '17 at 05:58
  • @ShubhamKhatri I did `this.props.history.push('/dashboard',this.state.values);` inside `setData` function but in console I got this `Error in loading Dashboard TypeError: Cannot read property 'setData' of undefined` error. I also tried `this.props.history.push({ pathname: '/dashboard', state: { values:data } })` What am I missing?? – noobie Sep 12 '17 at 06:27
  • Thats because you have to bind the success callback function of axios request and every function where you use `this` – Shubham Khatri Sep 12 '17 at 06:32
  • U mean `this.loadDashboard = this.loadDashboard.bind(this);` this? – noobie Sep 12 '17 at 06:36
  • I mean `.then( (response) => { console.log(response.data); //it works! this.setData(response.data) })` – Shubham Khatri Sep 12 '17 at 06:43
  • I did that and it redirects. Thanks. However in `Dashboard` component `console.log(this.props.location)` works but `console.log(this.props.location.state);` gives **TypeError: Cannot read property 'state' of undefined** but I defined `state` as you showed in your answer. I did `this.props.history.push({ pathname: '/dashboard', state: { values: data } })` – noobie Sep 12 '17 at 07:07
  • Two things, First, have you made use of withRouter, and second does this.props.location show you state. Also try and put a check for undefined and see what happens – Shubham Khatri Sep 12 '17 at 07:13
  • Yes `this.props.location` shows `state`. But doing `this.props.location.state` gives me error. – noobie Sep 12 '17 at 07:15
  • try this `if(this.props.location.state) {console.log(this.props.location.state)}` – Shubham Khatri Sep 12 '17 at 07:16
  • Did that. It is also giving me the same error. But doing `console.log(this.props.location)` gives **NO** error and shows value inside state > values – noobie Sep 12 '17 at 07:22
  • Sorry my mistake, didn't pay attention to error, This is what you need `if(this.props.location && this.props.location.state) {console.log(this.props.location.state)}` – Shubham Khatri Sep 12 '17 at 07:24
  • It works! Thank you so much! Can you please explain why that works & directly doing `this.props.location.state` gives error?? Also, why `.then( (response) => {..})` binds the success callback but not `.then(function(response) => {..})` ? What was the need for **binding the success callback** ?? Once again thankyou. – noobie Sep 12 '17 at 07:33
  • That happens because initially this.props.location may not be available and it is getting undefined, and then it updates, so you need to check if its available and then only use it. I am closing this as a duplicate since the other question helped you achieve what you wanted. – Shubham Khatri Sep 12 '17 at 08:23
  • @ShubhamKhatri Can this solution may cause [this](https://stackoverflow.com/questions/46172768/how-to-use-constructor-value-outside-constructor) issue?? – noobie Sep 12 '17 at 10:16

0 Answers0