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?