Member-only story
React basic 5 — Basic Event Handlers
Now we went over basic class structures from the last post (React basic 4 — Class Based Component and Lifecycle Methods), I would like to go over handling events. The key is the use of props to invoke a method of a parent Class from its child Class's event, which comes at the end of this post.
In the next few posts, we will be creating a simple image search app like this.
Basic event handler
For the very basic event handler, we can create a method and invoke the event from a DOM event object. As you can see from below example, a method can be called from JSX using {} syntax. This method just console-logs what a user typed.
import React from ‘react’;class SearchBar extends React.Component {
onInputChange = e => {
console.log(e.target.value);
} render() {
return (
<div className = “ui segment”>
<form className=”ui form”>
<div className =”field”>
<input type = “text”
onChange={ this.onInputChange } />
</div>
</form>
</div>
);
}};export default SearchBar;