Forked from sergiodxa/react-event-handler-papp-props.jsx
Created
January 16, 2017 03:28
-
-
Save vasanthk/d7c067bc2fd1293c7c4b80116a749581 to your computer and use it in GitHub Desktop.
Example of how to use partial application to pass parameters to event handlers in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // with props | |
| import React, { Component } from 'react'; | |
| // this method work as a our base `handleClick` function | |
| function handleClick(name, event) { | |
| alert(`hello ${name}`); | |
| } | |
| class App extends Component { | |
| constructor(props) { | |
| super(props); | |
| this.handleClick = handleClick.bind(this, props.name); | |
| } | |
| // if the prop `name` change re bind the `handleClick` | |
| componentWillReceiveProps(nextProps) { | |
| if (nextProps.name !== this.props.name) { | |
| this.handleClick = handleClick.bind(this, nextProps.name); | |
| } | |
| } | |
| render() { | |
| return ( | |
| <div onClick={this.handleClick}> | |
| hola mundo | |
| </div> | |
| ); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // with state | |
| import React, { Component } from 'react'; | |
| // this method work as a our base `handleClick` function | |
| function handleClick(name, event) { | |
| alert(`hello ${name}`); | |
| } | |
| class App extends Component { | |
| constructor(props) { | |
| super(props); | |
| this.state = { name: 'Platzi' }; | |
| this.handleChange = this.handleChange.bind(this); | |
| this.handleClick = handleClick.bind(this, this.state.name); | |
| } | |
| // if the state `name` change re bind the `handleClick` | |
| componentWillUpdate(nextProps, nextState) { | |
| if (nextState.name !== this.state.name) { | |
| this.handleClick = handleClick.bind(this, nextState.name); | |
| } | |
| } | |
| handleChange(event) { | |
| this.setState({ name: event.target.value }); | |
| } | |
| render() { | |
| return ( | |
| <div> | |
| <button onClick={this.handleClick}> | |
| click me! | |
| </button> | |
| <input | |
| type="text" | |
| value={this.state.name} | |
| onChange={this.handleChange} | |
| /> | |
| </div> | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment