Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing function through Switch Route component

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading