Andrew Kim Andrew Kim - 26 days ago 7
React JSX Question

React Link onClick not leveraging current params

Let's same i'm rendering some React Component and its render looks like this:

render(){
let links = [10, 50, 100, 500, 1000].map((num) => {
return(
<Link key={num} onClick={this.showParams.bind(this)} to={`/somePath/${num}`}>{num}</Link>
)
})
return (
<div>{links}</div>
)
}


And I have the following function defined in the same component:

showParams(){
console.log(this.props.params);
}


Whenever I click a link, it's logging what the params value was before the link was clicked, not after the link was clicked. How can I get my react component to access the
props.params
garnered from this link itself. Or should I be taking a completely different approach. It does feel a little off that I need an
onClick
(i eventually want to reset the state with this new parameter, that seems like something the Link component should do inherently).

If it helps here's the part of my router that's pertinent:

<Route path='/somePath/:num' component={someComponent} />

Answer

ES6

Use an arrow function:

return (
  <th value={column} onClick={() => this.handleSort(column)}>{column}</th>
);

ES5

You can use .bind to pass the parameter you want:

return (
  <th value={column} onClick={that.handleSort.bind(that, column)}>{column}</th>
);
Comments