John
John

Reputation: 127

Navigate in react using react-router-dom 6

I am working on a React app where I am trying to navigate from a loginform to the homescreen of my app using an onSubmit function. This is what I have so far. In my formik form im trying to pass the email value when the form gets submitted. After that the user gets routed to '/dashboard' and ends up in '/dashboard/app' where im trying to get the email value logged in the console. I tried logging route.params and route.email but this gives either undefined or errors.

enter image description here

enter image description here

enter image description here

Upvotes: 2

Views: 6433

Answers (2)

Krushnasinh Jadeja
Krushnasinh Jadeja

Reputation: 624

Did you mean to add state to the navigation?

Original:

onSubmit: () => {
          navigate('/dashboard', {replace:true, email: values.email})
}

Changed to (with state):

onSubmit: () => {
          navigate('/dashboard', {replace:true,
                                  state: { 
                                           email:values.email
                                          }
                                   })
}

Upvotes: 6

Branislav Lazic
Branislav Lazic

Reputation: 14806

As far as I understand, you want to redirect with some params. The easiest solution is to use "history push" with the state.

import { useHistory } from "react-router-dom";

const LoginForm = () => {
  const history = useHistory();
  const formik = useFormik({
    onSubmit: () => {
      history.push('/dashboard', {replace: true, email: values.email})
    }
  })
}

In a similar manner access history state by: history.state

Upvotes: 0

Related Questions