I am using react with ES6 and want to reuse a variable at class level. I get an error:
bundle.js:29225 Uncaught TypeError: Cannot read property 'tempUnits' of undefined
My code is here
class WeatherList extends Component {
constructor(){
super();
this.tempUnits = 'C'; // <== initialise it here
}
renderWeather(cityData) {
console.log('tempunits', this.tempUnits); // <== blows up here
const name = cityData.city.name;
const temps = _.map(cityData.list.map(weather => weather.main.temp), (temp) => temp-273);
const pressures = cityData.list.map(weather => weather.main.pressure);
const humidities = cityData.list.map(weather => weather.main.humidity);
const { lon, lat } = cityData.city.coord;
return (
<tr key={name}>
{/* <td><GoogleMap lon={lon} lat={lat} /></td> */}
{/* <== Use it here */}
<td><Chart data={temps} color="orange" units="{this.tempUnits}" /></td>
<td><Chart data={pressures} color="green" units="hPa" /></td>
<td><Chart data={humidities} color="black" units="%" /></td>
</tr>
);
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
{/* <== Reuse it here again */}
<th>Temperature ({this.tempUnits})</th>
<th>Pressure (hPa)</th>
<th>Humidity (%)</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
);
}
}
Questions I want to reuse the tempUnits variable across functions within the class. How do I do this?