Hi all.
I’m learning React and trying to reinforce some of the basic concepts that I’ve seen but I’m running into a number of issues. I’m wondering if someone could help me understand why my code is not working. I am trying to generate a list using the map function and make it so that each item, when clicked, will console log what was clicked. Everything is working fine, but when I add the ‘onClick’ piece to the li that is being returned, the code breaks with an error of ‘Cannot read property of ‘showLanguage’ of undefined’.
class MyApp extends React.Component {
constructor(props) {
super(props);
this.showLanguage = this.showLanguage.bind(this);
}
showLanguage(lang) {
console.log(lang);
}
render() {
var languages = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'];
return (
<div>
<ul className='languages'>
{languages.map(function(lang) {
return (
<li onClick={this.showLanguage}>{lang}</li>
)
})}
</ul>
</div>
)
}
}