I would like to learn how is the value of 'this' set when a function called in JSX as a callback to an eventHandler. I noticed that when I call it directly there is no issue accessing state without getting the famous undefined 'this' error, like so:
import React from "react";
class Accordion extends React.Component {
state = { term: "random term" };
onTitleClick() {
console.log("Title is clicked");
console.log(this.state.term);
}
render() {
const renderedItems = this.props.items.map((item) => {
return (
<React.Fragment key={item.title}>
<div className="title active" onClick={this.onTitleClick()}>
<i className="dropdown icon"></i>
{item.title}
</div>
<div className="content active">
<p>{item.content}</p>
</div>
</React.Fragment>
);
});
return <div className="ui styled accordion">{renderedItems}</div>;
}
}
export default Accordion;
When you pass it as just a reference, the famous 'this' is undefined error comes back. Then we know how to bind the 'this' and so on. I feel like I just memorized the solution and now would like to learn the difference.