Created
April 21, 2023 01:46
-
-
Save reboottime/4cec1d85104ddd1549a04e106fa58fa8 to your computer and use it in GitHub Desktop.
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
import React, { useRef, useEffect, RefObject, forwardRef } from "react"; | |
interface FormProps { | |
onSubmit?: (event: React.FormEvent<HTMLFormElement>) => void; | |
} | |
const Form = forwardRef<HTMLFormElement, FormProps>((props, ref) => { | |
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { | |
event.preventDefault(); | |
console.log("Form submitted"); | |
if (props.onSubmit) { | |
props.onSubmit(event); | |
} | |
}; | |
return ( | |
<form ref={ref} onSubmit={handleSubmit}> | |
<label> | |
First Name: | |
<input type="text" name="firstName" /> | |
</label> | |
<label> | |
Last Name: | |
<input type="text" name="lastName" /> | |
</label> | |
<button type="submit">Submit</button> | |
</form> | |
); | |
}); | |
function App() { | |
const formRef = useRef<HTMLFormElement>(null); | |
useEffect(() => { | |
console.log(formRef.current); // will log the form element | |
}, []); | |
return <Form ref={formRef} />; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment