Skip to content

Instantly share code, notes, and snippets.

@felquis
Created February 18, 2023 15:18
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 felquis/8e4793e16846dd250716f58a528ae7a1 to your computer and use it in GitHub Desktop.
Save felquis/8e4793e16846dd250716f58a528ae7a1 to your computer and use it in GitHub Desktop.
Use this callback on all input's onChange prop, inputs must have proper type and name matching the state
function Example() {
const defaultInputValues = {
name: "", // should match input's name prop
email: "",
address_line_1: "",
birthday: "",
}
const [controlledFields, setControlledFields] = useState({
...defaultInputValues,
})
const onControlledInputChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
let value
if (event.target.type === "number") {
value = Number.isInteger(event.target.valueAsNumber)
? event.target.valueAsNumber
: ""
} else if (event.target.type === "text") {
value = event.target.value
} else if (event.target.type === "date") {
value = event.target.valueAsDate
? formatInDateInUTC(new Date(event.target.valueAsDate), "yyyy-MM-dd")
: ""
} else {
value = event.target.value
}
const newControlledValues = {
...controlledFields,
[event.target.name]: value,
}
setControlledFields({
...newControlledValues,
...calculatedFieldsBasedOnNewControlledInputValues(newControlledValues),
})
},
[
setControlledFields,
controlledFields,
calculatedFieldsBasedOnNewControlledInputValues,
]
)
return <>...</>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment