Search code examples
reactjsnext.jsreact-hook-formchakra-ui

How can redirect to confirmation page with react-hook-form?


I am working on a form with nextjs13, chakra-ui, react-hook-form.

There's a text input field where user put email address. (url is xxx/new)

here's form I have:

export const NewForm = () => {
    const {
        register,
        handleSubmit,
        formState: { errors },
        trigger,
        watch,
    } = useForm<NewFormType>();

   
    const onSubmit = handleSubmit((data) => {
        //do something
        console.log(data);
    });

    return (
        <Box>
            <Box>
                <form onSubmit={onSubmit}>                      
                  <FormControl isInvalid={!!errors[`email`]}>
                     <Input
                       id={"email"}
                       type={"email"}
                       {...register("email", {
                                    required: "required",   
                       })}
                     />
                   </FormControl>
                </form>
                <Box>
                    <Button>Confirm</Button>
                </Box>
            </Box>
        </Box>
    );
};

When user hits 'Confirm' button, I want to move to the confirmation page with url xxx/confirm and show whatever user put.

I know that I can show/hide confirm component using state variable if the form and confirmation component on the same page but not sure when they are not on the same page.
(also, I cannot use query parameter)

Is there any hook I can use? or should I use Provider in this case?


Solution

  • Here you can use useRouter Hook to redirect to the confirm page and React context to pass data between component. You just need to create context and then store it's value inside the onSubmit handler like shown below

    const { setFormData } = useConfirmationContext();
    
    const onSubmit = handleSubmit((data) => {
        // set the form data in the context
        setFormData(data);
        // navigate to the confirmation page
        router.push(`xxx/confirm`);
    });
    

    and then you can get the data in the confirmation page like below

    const { formData } = useConfirmationContext();
    

    Please try this way and update.