While looking into the react sample app, I came across a scenario whereby you might need to pass a specific piece of data across to an event handler. A lot of the online examples cover data state; but what happens when you have a situation such as the one in the sample app; consider this:
In this instance, you want to pass the temperature of the line you’ve selected. The solution is quite simple, and documented here:
private renderForecastsTable(forecasts: WeatherForecast[]) {
return <table className='table'>
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
{forecasts.map(forecast =>
<tr key={ forecast.dateFormatted }>
<td>{ forecast.dateFormatted }</td>
<td>{ forecast.temperatureC }</td>
<td>{ forecast.temperatureF }</td>
<td>{forecast.summary}</td>
<td><button onClick={(e) => this.handleClick(e, forecast)}>Log Temperature!</button></td>
</tr>
)}
</tbody>
</table>;
}
Here, we’re passing the entire forecast object to the handler; which looks like this:
handleClick = (event: React.FormEvent<HTMLButtonElement>, forecast: WeatherForecast) => {
console.log("timestamp: " + event.timeStamp);
console.log("data: " + forecast.temperatureC);
}