Tuesday, August 7, 2018

Event handler example in React

Event handlers are used to handle various events arising from controls in React components. Event handlers are functions in react component, event handlers are bound to events in React components in the constructor or the component using bind()

this.handleClick = this.handleClick.bind(this);

In this example the react component has a buttons, the click event of the button is bound to a handler function handleClick(). In the handler we change the state of the component.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';

class HelloState extends Component {
  constructor(props) {
    super(props);
    this.state = {
show: false
};
this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {    
    this.setState({show : !this.state.show});
  }

  render() {
return (
  <div>
<div>
<button onClick = {this.handleClick}> Show/Hide </button><br/>
{ this.state.show ?
<span>Hello State</span>
:
null
}
</div>
  </div>
);
  }
}

ReactDOM.render(<HelloState />, document.getElementById('app'));

Search Flipkart Products:
Flipkart.com

No comments: