Skip to content

Instantly share code, notes, and snippets.

@richleach
Created April 21, 2021 21:40
Show Gist options
  • Save richleach/4ab3d25b0972eba955210fc1da26262f to your computer and use it in GitHub Desktop.
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.
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