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?
2
Answers
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
and then you can get the data in the confirmation page like below
Please try this way and update.
There are many ways to share states through multiple components like context api or other state management libraries and etc.
In my opinion if you’re already using react-hook-form, you’d better use built-in ‘useFormContext’ hook of react-hook-form.
https://www.react-hook-form.com/api/useformcontext/
Also, If you’d like to navigate page to page in next.js, you might have to use router from ‘next/navigation’.
maybe like this,