Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.