Skip to content

Instantly share code, notes, and snippets.

@reboottime
Created April 21, 2023 01:46
Show Gist options
  • Save reboottime/4cec1d85104ddd1549a04e106fa58fa8 to your computer and use it in GitHub Desktop.
Save reboottime/4cec1d85104ddd1549a04e106fa58fa8 to your computer and use it in GitHub Desktop.
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