Programmatical Navigation

When we want to navigate through the pages in function or if a condition is satisfied, we use the hook:

useNavigate

This hook provides a function called useNavigate()

import { useNavigate } from 'react-router-dom'

const Signup = () => {
  let { register, handleSubmit, formState: { errors } } = useForm()
  let [regUsers, setRegUsers] = useState([])
  let navigate = useNavigate()

  function handleFormSubmit(data) {
    setRegUsers([...regUsers, data])
    navigate('/regusers')
  }
  return <></>
}

In the above example, when the handleFormSubmit() is called, the page navigates to /regusers navigate(’/regusers’) .

And we can also send the data through this hook:

function handleFormSubmit(data) {
    navigate('/regusers',{state:regUsers})
}

RegUsers.jsx

import React, { useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom'
const RegUsers = () => {
    let location = useLocation()
    let [regUsers, setRegUsers] = useState([])
    let {state}=useLocation()
    useEffect(() => {
        setRegUsers([...regUsers,state])
    },[])
  return (
    <div>
        <h2>Registered Users</h2>
        <table>
          <thead>
            <tr>
              <th>Username</th>
              <th>Email</th>
            </tr>
          </thead>
          <tbody>
            {regUsers.map((user, index) => (
              <tr key={index}>
                <td>{user.username}</td>
                <td>{user.email}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
  )
}
export default RegUsers