- register input with
register('email')
function - inject the output from register in input.
<input {...register('name')}/>
- pass the
handleSubmit
function fromuseForm()
and avoid this<form onSubmit={handleSubmit((data) => console.log(data))}>...</form>
<form onSubmit={() => handleSubmit(callback)}>...</form>
- inside the
form
there should be at least a button or type='submit'
register()
takes two params. First is name and second one is options which is optional. show more{...register("email", { required: "Email is required" })}
this required field will return as a message.- find the error at
const {formState : {errors}} = useForm()
Private Route using React router
- create a component that returns it's children on condition.
const PrivateRoute = ({ children }) => {
if (user?.uid) return children;
return <>Loading...</>;
};
export default PrivateRoute;
- now wrap any component with
PrivateRoute
{
path: "/",
element: (
<PrivateRoute>
<Home />
</PrivateRoute>
),
},
- Go to different page if condition doesn't full fill
const PrivateRoute = ({ children }) => {
if (user?.uid) return children;
return <Navigate to={"/signin"}></Navigate>;
};
- use
Navigate
component instead ofuseNavigate()
hook there.
const PrivateRoute = ({ children }) => {
const navigate = useNavigate();
const { user } = useContext(User);
if (user?.uid) return children;
else navigate("/signin");
};
useNavigate
works on events only
- navigate with state & replace
//private route.jsx
const PrivateRoute = ({ children }) => {
const { pathname } = useLocation();
if (user?.uid) return children;
return <Navigate state={{ pathname }} to={"/login"} replace></Navigate>;
// navigated from pathname
// passing a props named state
};
state props will be injected to the location of
/login
- get the pathname
// login.jsx
const {
state: { pathname },
} = useLocation();
// location.state.pathname // state={{ pathname }}
- now we know the previous location and go with
//login.jsx
setTimeout(() => navigate(pathname || '/'), 100);
// go to root route if pathname not available