skip to Main Content

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


  1. react-hook-form handles the preventDefault() automatically so you dont need to explicitly call it.

    export default function App() {
        const {register, handleSubmit} = useForm();
      
        const onSubmit = (data) => {
            console.log(data);
        };
      
        return (
            <Box sx={{pt:15}}>
                <form onSubmit={handleSubmit(onSubmit)}>
                    <input {...register("firstName")} placeholder='First Name'/>
                    <input {...register("lastName")} placeholder='Last Name'/>
                    <input type='submit'/>
                </form>
            </Box>
        );
    }
    
    Login or Signup to reply.
  2. 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.

    '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();
      const onSubmit = React.useCallback((data, e:any): void => {
            console.log(data)
            e.preventDefault()
            
      }, [])
      
    
      return (
        <Box sx={{pt:15}}>
        <form onSubmit={handleSubmit(onSubmit)}>
            <input {...register("firstName")} placeholder='First Name'/>
            <input {...register("lastName")} placeholder='Last Name'/>
            <input type='submit'/>
        </form>
        </Box>
      );
    }
    

    https://react.dev/reference/react/useCallback
    https://react.dev/reference/react/useMemo
    https://react.dev/reference/react/useMemo#skipping-re-rendering-of-components

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search