I am trying to make a form and obviously do not want the page to refresh on submit but I am struggling to make this happen. Here’s the code:
'use client'
import * as React from 'react';
import {useForm} from "react-hook-form"
import Box from '@mui/material/Box';
export default function App() {
const {register, handleSubmit} = useForm();
return (
<Box sx={{pt:15}}>
<form onSubmit={handleSubmit((data, e:any): void => {
console.log(data)
e.preventDefault()
})}>
<input {...register("firstName")} placeholder='First Name'/>
<input {...register("lastName")} placeholder='Last Name'/>
<input type='submit'/>
</form>
</Box>
);
}
I have tried messing aorund with slight changes but nothinfg seems to be working. Any ideas on what I am doing wrong? Thanks.
2
Answers
react-hook-form
handles thepreventDefault()
automatically so you dont need to explicitly call it.Try placing the onSubmit handler function in a
useCallback
, or if there are other data that you’re sure wouldn’t change you can memoize it. So react wouldn’t re-render unnecessarily for those methods or functions.https://react.dev/reference/react/useCallback
https://react.dev/reference/react/useMemo
https://react.dev/reference/react/useMemo#skipping-re-rendering-of-components