Hi,
I’m using react router in my application and for a specific route path, I wanted to pass in the state of parents to the props of child. I suspect that something async is going on because in line 85, the console log printed out this.state.page, but in line 86 it says this.state.page is undefined. Here is the code:
import React, { Component } from 'react';
import { BrowserRouter } from "react-router-dom";
import { Route, Switch, Redirect } from "react-router-dom";
import './App.css';
import {allrecipe} from "./recipes.js";
import {About} from "./About.js"
import {Recipe} from "./Recipe.js"
function importAll(r) {
return r.keys().map(r);
}
const images = importAll(require.context('./image', false, /\.(png|jpe?g|svg)$/));
const Header = () => (
<div className="header">
<span className="header-title"> The Omnivore's plate </span>
<a href="/about" className="header-span"> About me</a>
<a href="/" className="header-span"> Recipes</a>
</div>
);
class List extends React.Component {
constructor(props) {
super(props);
this.props = props.obj;
//this.state = {currentRecipe: props.obj.wid};
}
render(){
if (this.props.state !== "home") {
return <Redirect to={this.props.state} />
}
return(
<ul className="list">
{ this.props.obj.map(prop =>
<li className="gridwrapper" id={prop.wid} onClick={()=> this.props.action(prop.wid)}>
<div className="grid">
<div className="flex-column" >
<div className="photo-wrapper">
<img src={images[prop.index]} width="200" height="250"></img>
</div>
<div className="name-wrapper">
<p>{prop.name}</p>
</div>
<div className="flex-row">
<div className="time-wrapper">
<p className="content">Total time: {prop.total_time}</p>
</div>
<div className="serving-wrapper">
<p className="content">Serving: {prop.serving}</p>
</div>
</div>
</div>
</div>
</li> )}
</ul>
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.pageSwitch = this.pageSwitch.bind(this);
this.state = {
page: "home"
};
}
pageSwitch(newState) {
this.setState({
page: newState
});
}
render() {
console.log(this.state.page);
return (
<div>
<Header></Header>
<BrowserRouter>
<Switch>
<Route exact path="/" render={()=><List obj={allrecipe} action={this.pageSwitch} state={this.state.page}/>} />
<Route path="/about" component={About} />
{console.log(this.state.page)}
<Route path="/:recipe" render={function(){Recipe(this.state.page)}} />
}
</Switch>
</BrowserRouter>
</div>
);
}
}
export default App;
Thanks!
Edit: Actually I just solved it. Never mind !