Skip to content

Instantly share code, notes, and snippets.

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 manuelbieh/b1a6715e2c2e2a96b5195ee66acc1a9b to your computer and use it in GitHub Desktop.
Save manuelbieh/b1a6715e2c2e2a96b5195ee66acc1a9b to your computer and use it in GitHub Desktop.
onChange = (e: React.ChangeEvent) => {
e.persist();
const {
target: { checked, name, type, value },
} = e;
if (!name && process.env.NODE_ENV === 'development') {
console.warn(
`Change event with value '${value}' happened for an element without name prop. This is probably by mistake.`
);
}
// TODO: figure out if this is really such a good idea
this.resetError(name);
// TODO: make this more flexible (see the work that has been done in array-parser.js for more)
if (type === 'checkbox') {
if (!value || value === 'on') {
return this.setState((state) => ({
values: {
...state.values,
[name]: checked ? 'on' : undefined,
},
}));
}
return this.setState((state) => ({
values: {
...state.values,
[name]: (checked
? (Array.isArray(state.values[name])
? state.values[name]
: []
).concat(value)
: (Array.isArray(state.values[name])
? state.values[name]
: []
).filter((item) => item !== value)
).reduce(
(acc, item) => (item ? (acc || []).concat(item) : acc),
undefined
),
},
}));
}
this.setValue(name, value);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment