Home > Blockchain >  How to get props from <Route /> with react router dom v6
How to get props from <Route /> with react router dom v6

Time:02-19

I am trying to pass :id to url when i click a row of my table trying using navigate("/edit/" props); and onClick={() => handleClick(data.PacienteId)} but it didnt work then used useParams and created handleProceed to use it as onclick={handleProceed} but it still not working i just get url provided by Apiurl but /undefined

This is what i have in my routes

function App() {
  return (
    <>
      <BrowserRouter>
        <Routes>
          <Route path="/" exact element={<Login  />} />
          <Route path="/dashboard" exact element={<Dashboard  />} />
          <Route path="/new" exact element={<Nuevo  />} />
          <Route path="/edit/:id" exact element={<Editar />} />
        </Routes>
      </BrowserRouter>
    </>
  );
}

This is my dashboard where i want to pass id to url clicking on table

export const Dashboard = (props) => {
  const [paciente, setPaciente] = useState([]);
  const {id}=useParams();
  const navigate = useNavigate();
  useEffect(() => {
    let url = `${Apiurl}pacientes?page=1`;
    axios.get(url).then((response) => {
      setPaciente(response.data);
    });
  }, []);

  const handleClick = (props) => {
    /* navigate("/edit/"   props); */
    navigate(`/edit/${id}`);
  };
  const handleProceed = (e) => {
    /* history.push(`/edit/${id}`); */
    navigate(`/edit/${id}`);
  };
  return (
    <>
      <Header />
      <div className="container">
        <table className="table table-dark table-hover">
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">DNI</th>
              <th scope="col">NOMBRE</th>
              <th scope="col">TELEFONO</th>
              <th scope="col">CORREO</th>
            </tr>
          </thead>
          <tbody>
            {paciente.map((data, i) => {
              return (
                <tr key={i} /* onClick={handleProceed} */onClick={() => handleClick(data.PacienteId)}>
                  <td>{data.PacienteId}</td>
                  <td>{data.DNI}</td>
                  <td>{data.Nombre}</td>
                  <td>{data.Telefono}</td>
                  <td>{data.Correo}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

CodePudding user response:

try <Route path="/dashboard/:id" element={<Dashboard />} /> with this way you can get id in component DashBoard

is that what you mean?

CodePudding user response:

In your handle click function you have the parameter named as props, but you've tried to use "id" variable in the navigate method. Either use props in the navigate method or change the argument name to id.

 const handleClick = (id) => {
   navigate(`/edit/${id}`);
 };

********* OR ************

 const handleClick = (props) => {
   navigate(`/edit/${props}`);
 };
  • Related