1

I'm following the React for Beginner tutorial by using the React Router V4.However I can't get my params in my component.Here's part of my code.

const Root = () => {
return (
  <BrowserRouter>
    <div>
      <Switch>
          <Route exact path='/' component={StorePicker} />
          <Route Path='store/:storeId' component={App} />
          <Route component={NotFound} />
      </Switch>
    </div>
  </BrowserRouter>
)
}

StorePicker component:

class StorePicker extends React.Component {
    render() {
        return (
            <form className="store-selector" onSubmit={(e) => this.goToStore(e)}>
                <h2>Please Enter A Store</h2>
                <input type="text" ref={(input) => { this.storeInput= input; }} defaultValue={getFunName()} placeholder="Store Name" required/>
                <button type="submit">Visit Store</button>
            </form>
        )
    }

    goToStore(event) {
        event.preventDefault()
        const storeInput = this.storeInput.value
        console.log(storeInput)
        this.props.history.push(`store/${storeInput}`)
    }

}

And in my App component I can't get the storeId.

//storeId is undefine
this.props.match.params.storeId

What's wrong with my code?

Shawn Rong
  • 145
  • 3
  • 14

1 Answers1

2

React Router 4 has been re-vamped:

the router context is no longer injected into the props automatically (if i remember correctly this is how react router 3 worked, or depending on how you specified the context of the component that the router rendered).

try this:

import { withRouter } from 'react-router';

when exporting your component, wrap it:

withRouter(MyComponent)

this should correctly inject the props you are looking for so they arent undefined.

I took this directly from the react router site:

https://reacttraining.com/react-router/web/api/withRouter

Marrs
  • 706
  • 7
  • 10
  • So I should export my App component like export default withRouter(App)? – Shawn Rong Sep 13 '17 at 09:35
  • I'm not exactly sure but `withRouter` is for Components which is not directly related to Routes. Rather than passing props to each child you can use `withRouter` – bennygenel Sep 13 '17 at 09:35
  • Yea so declare your class at the top like: `class App extends React.Component`. then at the bottom `export default withRouter(App)`, granted i dont know your app setup, but i am assuming this is your problem of why its undefined – Marrs Sep 13 '17 at 09:38
  • just reviewed your code, and assuming it works, you would want to import withRouter in your `StorePicker` component, saw you mentioned `App`. – Marrs Sep 13 '17 at 09:48
  • I still can not get the router param. – Shawn Rong Sep 13 '17 at 09:50