0

I'm trying to pass props to a component using react router like so:

   <Login
            id={this.state.id}
            password={this.state.password}
            onChange={this.onChange}
            onSubmit={this.onSubmit}
            error={this.state.error}
          />

How do I do exactly that but with a react router, and how do I use it in the component itself?

I tried this but it doesn't work:

  <Route
            path="/"
            component={Login}
            components={{
              id: this.state.id,
              password: this.state.password,
              onChange: this.onChange,
              onSubmit: this.onSubmit,
              error: this.state.error
            }}
          />
Alexander
  • 1,288
  • 5
  • 19
  • 38

1 Answers1

1

Create Login component as child of route:

<Route path="/">
    <Login id={this.state.id} ... />
</Route>

UPD: As trixn noted, it is better to use render function to render component only when route matches

<Route path="/" render={ () => (
    <Login id={this.state.id} ... />
)}/>
pure cuteness
  • 1,635
  • 11
  • 26
  • Careful, the children of a `Route` are always rendered, not matter if the path matches or not. For rendering of a match use the `render` prop. – trixn Nov 29 '18 at 09:47
  • trixn can you write an aswer describing how to use render prop? I cant find a proper syntax anywhere. – Alexander Nov 29 '18 at 09:48
  • @AlexK please check the duplicate post – Shubham Khatri Nov 29 '18 at 09:49
  • @AlexK For reference: https://reacttraining.com/react-router/web/api/Route/render-func – trixn Nov 29 '18 at 09:49
  • trixn In that post hes not passing any props at all, so the syntax is not clear to me, i'm passing alot of props that contains callback functions, how do I write that? can you please write an example? I will delete this post after that.. I just want to know > – Alexander Nov 29 '18 at 09:51
  • @Shubham Khatri That post is incredibly unclear, I have no idea after reading it how to refer that to my question, a function render(props), what enters the props? how do I send it there?, please help> – Alexander Nov 29 '18 at 09:55
  • 2
    If only you tried to read the question and the answer properly, Anyways ` } />` – Shubham Khatri Nov 29 '18 at 09:59
  • @AlexK The props to the render function are the `Route` props and you can of course add your own props to the components that it renders. It's all clearly described in the documentation as well as in the duplicate questions answer. Please take your time to read that carefully and you can answer your question. – trixn Nov 29 '18 at 10:02