Created
April 21, 2021 21:40
-
-
Save richleach/4ab3d25b0972eba955210fc1da26262f to your computer and use it in GitHub Desktop.
Use the useRef hook to create an association of the form field/value to something React can use. Create a variable with useRef, then assign that variable to the form field's value. Easy-peasy.
This file contains hidden or 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
import { useRef } from 'react'; | |
function MyFunction() { | |
const titleInputRef=useRef(); | |
const addressInputRef=useRef(); | |
function submitHandler(event){ | |
event.preventDefault(); | |
const enteredTitle = titleInputRef.current.value; | |
const enteredAddress = addressInputRef.current.value; | |
//dont forget basic error trapping! | |
const myObjectToPassToServer = { | |
title: {enteredTitle}, | |
address: {enteredAddress} | |
} | |
console.log(myObjectToPassToServer); | |
} | |
return ( | |
<form onSubmit={submitHandler}> | |
<input type='text' required id='title' ref={titleInputRef} /> | |
<input type='text' required id='address' ref={addressInputRef} /> | |
</form> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment