Skip to content

Instantly share code, notes, and snippets.

@Paratron
Last active September 18, 2017 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Paratron/a0fbeda2b2e8cfd341f337b38cfff16d to your computer and use it in GitHub Desktop.
Save Paratron/a0fbeda2b2e8cfd341f337b38cfff16d to your computer and use it in GitHub Desktop.
React dynamic change handlers pattern
import React from 'react';
import PropTypes from 'prop-types';
const propTypes = {
firstName: PropTypes.string,
lastName: PropTypes.string,
birthDay: PropTypes.number,
gender: PropTypes.number,
}
export default class Example extends React.Component{
constructor(props){
super(props);
/**
* This is a pattern to dynamically define change handlers based on prop names!
* You can add/remove as many elements as you want and don't have to define handlers
* for all of them :)
*
* Se how it is being used in the render function!
*
* Note how this component is expected to pass an object with the changed values upwards,
* because of that we are using dynamic key assertion, but you can roll your own update mechanism.
*/
this.changeHandlers = {};
this.handleChange = (propName) => {
if(this.changeHandlers[propName]){
return this.changeHandlers[propName];
}
this.changeHandlers[propName] = v => this.props.onChange({ [propName]: v });
return this.changeHandlers[propName];
}
}
render(){
const {
firstName,
lastName,
birthDay,
gender,
} = this.props;
return (
<div>
<TextInput
value={firstName}
onChange={this.handleChange('firstName')}
/>
<TextInput
value={lastName}
onChange={this.handleChange('lastName')}
/>
<DatePicker
value={birthDay}
onChange={this.handleChange('birthDay')}
/>
<GenderSelector
value={gender}
onChange={this.handleChange('gender')}
/>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment