ga-wdi-exercises/project4

Can't get url params in component

Closed this issue · 13 comments

I have a parent component App and child component Dashboard. I route to Dashboard like this

render() {
    let self = this
    let event = function(){
      return <Dashboard myMap={self.state.thisMap} data={self.state.sendData} layers={self.state.layers.michigan}/>
    }
    return (
<Router>

           <Route path="/events/:name" component={event} />
</Router>

)

Inside of Dashboard, I am trying to get the url param :name but this.props.location is coming up as undefined.

class Dashboard extends Component {
  constructor(props){
    super(props)
    this.state = {
      name: this.props.location.name,
  }
}

change <Route>'s component prop to render, since it only passes in location, history, and match as props. Reference

Like this?

<Route path="/events/:name" render={() => <Dashboard myMap={self.state.thisMap} data={self.state.sendData} layers={self.state.layers.michigan}/>} />

It's still coming up as undefined.

Ah okay, are you passing an object in the to prop of the <Link /> component? Could you post that code?

This is my link to go to the child component:

<Link to={this.state.pathName}>
     <div className="info" onClick={this.closeButton}>Go to Component</div>
</Link>

You just the data from params right? If that's the case, it seems like you can still use the component prop and access the value of :name with this.props.match.params. Try console.logging that in the constructor method of Dashboard.

Are you able to see the value of the :name param when you log this.match.props.params?

I couldn't get params to work but I edited my Link to this and it seems to be working now.

    <Link to={{pathname: self.state.pathName, state: {name: self.state.name}}}>
            <div className="info" onClick={self.closeButton}>Go to Component</div>
    </Link>

then I used name: this.props.location.state.name and it's no longer undefined. Not sure exactly what I changed beyond that.

That's because you're explicitly passing an object (state) in the value of <Link>'s to prop. Does that make sense?

You should be able to see the value of :name in this.location.match.params (this is provided by React Router) in your Dashboard props, though

I think so. I think defining the pathname in the Link made a difference as well. Once I did that it was able to read this.props.location.

closing for now! re-open if necessary