It is really frustrating to write many functions to handle events on multiple elements. Here we can use Javascript closure concept to avoid multiple functions. Observe below code

To Run Example Code

execute below commands
npm install
npm start
now open index.html in browser

Program

Here commonFunction is handling click events on multiple elements by using Javascript closure concept
import React from 'react'

class ExampleApplication extends React.Component {

  constructor(props) {
    super(props);
    this.commonFunction = this.commonFunction.bind(this);
    this.state = {
      message:''
    };
  }

  commonFunction(itemName) {
    const _this = this;
    return function() {
      _this.setState({
        message:'clicked on '+itemName+'....take some action'
      });
    }
  }

  render() {
    return (
      <div>
         Click on below list items<br/><br/>
         <b>{this.state.message}</b><br/>
         <ul>
           <li onClick={this.commonFunction('item 1')}>List item 1</li>
           <li onClick={this.commonFunction('item 2')}>List item 2</li>
           <li onClick={this.commonFunction('item 3')}>List item 3</li>
           <li onClick={this.commonFunction('item 4')}>List item 4</li>
           <li onClick={this.commonFunction('item 5')}>List item 5</li>
         </ul>
      </div>
    );
  }

}

ExampleApplication.propTypes = {
}

ExampleApplication.defaultProps = {
}

export default ExampleApplication;

0 comments:

Blogroll

Follow this blog by Email

Popular Posts