Created
February 18, 2023 15:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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