Skip to content

Instantly share code, notes, and snippets.

@sergiodxa
Last active September 24, 2018 04:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sergiodxa/0c173d554b0d1f2a8006124be81c1915 to your computer and use it in GitHub Desktop.
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
// 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>
);
}
}
// 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