I want to build an app, which collects input information from sub-components and lift this information up to my main App component. I am using Switch with multiple Route to navigate through my questionnaire. I am able to pass variables and functions through my app until the <Switch> statement.
My problem: how do I pass a function or variable into my <Route> component.
class App extends Component {
state = {
date: new Date(),
machineid: null,
};
handleChangeMachine(event) {
const machineid_temp = event.target.value;
this.setState({machineid: machineid_temp})
console.log(machineid_temp)
}
render(){
return (
<div className="page">
<Router>
<Header testvalue="this is working"/>
<Switch testvalues="this is working">
<Route testvalues="this is not working" path="/" exact component={Landingpage}/>
<Route path="/survey" component={Survey}/>
<Route path="/kontakt" component={Kontakt}/>
<Route path="/question_one" handleChangeMachine={this.handleChangeMachine} component={question_one}/> {/* This is not working */}
<Route path="/question_two" component={question_two}/>
</Switch>
</Router>
</div>
);
}
}
export default App;
In this case the function handleChangeMachine isn't properly passed to the component question_one. Has anyone an idea about how I can solve it? I've tried every thing I understood as a React-beginner.
CodePudding user response:
If you are using React-router@v5, you can write your route as follow:
<Route path="/question_one">
<QuestionOne handleChangeMachine={this.handleChangeMachine.bind(this)}
</Route>
Note that question_one
isn't a correct component name.
Or even :
<Route
path="/question_one"
render={({ match }) => {
// Do whatever you want with the match...
return <QuestionOne handleChangeMachine={this.handleChangeMachine.bind(this)} />;
}}
/>
You can check the documentation for more information.
Here is a repro on Stackblitz.
CodePudding user response:
Try this solution
class App extends Component {
state = {
date: new Date(),
machineid: null,
};
handleChangeMachine(event) {
const machineid_temp = event.target.value;
this.setState({machineid: machineid_temp})
console.log(machineid_temp)
}
render(){
return (
<div className="page">
<Router>
<Header testvalue="this is working"/>
<Switch testvalues="this is working">
<Route testvalues="this is not working" path="/" exact component={Landingpage}/>
<Route path="/survey" component={Survey}/>
<Route path="/kontakt" component={Kontakt}/>
<Route path="/question_one">
<question_one handleChangeMachine={this.handleChangeMachine.bind(this)} /> // rename component with UpperCase and without "_"
</Route>
<Route path="/question_two" component={question_two}/>
</Switch>
</Router>
</div>
);
}
}
export default App;