Last active
September 24, 2018 04:48
-
-
Save sergiodxa/0c173d554b0d1f2a8006124be81c1915 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