Created
August 22, 2022 05:50
-
-
Save adeleke5140/46a4028b4b34de8e3a1f8ddbe230d5dd to your computer and use it in GitHub Desktop.
Easy way to get Form values in React
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
//Given a form, | |
<form onSubmit={props.submitLaunch}> | |
<label htmlFor="launch-day">Launch Date</label> | |
<input type="date" id="launch-day" name="launch-day" min={today} max="2040-12-31" defaultValue={today} /> | |
<label htmlFor="mission-name">Mission Name</label> | |
<input type="text" id="mission-name" name="mission-name" /> | |
<label htmlFor="rocket-name">Rocket Type</label> | |
<input type="text" id="rocket-name" name="rocket-name" defaultValue="Explorer IS1" /> | |
<label htmlFor="planets-selector">Destination Exoplanet</label> | |
<select id="planets-selector" name="planets-selector"> | |
{selectorBody} | |
</select> | |
</form> | |
//add in a submitLaunch props which is a function that processes the formData | |
//the submitLaunch function would contain the following | |
const submitLaunch = useCallback(async (e) => { | |
e.preventDefault(); | |
const data = new FormData(e.target); | |
const launchDate = new Date(data.get("launch-day")); | |
const mission = data.get("mission-name"); | |
const rocket = data.get("rocket-name"); | |
const target = data.get("planets-selector"); | |
const response = await httpSubmitLaunch({ | |
launchDate, | |
mission, | |
rocket, | |
target, | |
}); | |
//useCallback which is used to return a memoized callback | |
//data.get is then used to extract the value of the form with their respective IDs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment