2

I'm trying to redirect to another page with passing data after submitting form in using react-router-dom v6. When I will click on submit, data will be submited and the application will take me to the "Download PDF" page, also the form data will pass registration page to the "Download PDF" page.

Example Code:

ConfirmRegistration.js

import React, { useState } from "react";
import { Navigate } from "react-router-dom";

const ConfirmRegistration = () => {
  const [name, setName] = useState();
  const [confirm, setConfirm] = useState(false);

  const handleOnChange = (e) => {
    e.preventDefault();
    const value = e.target.value;
    setName(value);
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    setConfirm(true);
    console.log(name);
  };

  if (confirm) {
    return (
      <Navigate
        to={{
          pathname: "/download-pdf",
        }}
      />
    );
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type='text'
          name='name'
          placeholder='input text here'
          onChange={handleOnChange}
        />
        <button type='submit'>Submit</button>
      </form>
    </div>
  );
};

export default ConfirmRegistration;

DownLoadPdf.js

import React from "react";

const DownLoadPdf = () => {
  return (
    <div>
      <p>DownLoad Pdf</p>
    </div>
  );
};

export default DownLoadPdf;
Rafael Tavares
  • 5,678
  • 4
  • 32
  • 48

3 Answers3

3

You can use useNavigate instead of using Navigate

import React, { useState } from "react";
import { useNavigate } from "react-router-dom";

const ConfirmRegistration = () => {
  const [name, setName] = useState();
  const [confirm, setConfirm] = useState(false);
  const navigate = useNavigate();
  const handleOnChange = (e) => {
     e.preventDefault();
     const value = e.target.value;
     setName(value);
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    setConfirm(true);
    console.log(name);
    navigate('/download-pdf', {state:// Your data})
  };
hassanqshi
  • 353
  • 2
  • 9
1

You can Use Hook Provided By React Router

 import { useNavigate } from "react-router-dom";
    
 const confirmRegistration = () => {
    const navigate = useNavigate();
    const handleSubmit = (e) => {
       ...
        navigate('/route', {state: {//pdfData}})
      };
    }

Other Way : You can store Data in a Global State and use from there. Redux, ContextAPI etc

Muhammad Bilal
  • 113
  • 2
  • 8
0

You're trying to pass data between components. There are several ways as using "Redux" state management, "Context API" and etc. Then in DownLoadPdf component you manipulate the data. If the project is high-scale, prefer using a statemanagement like "Redux". But you can simply pass data by navigate as this:

navigate('/download-pdf', {state: // The Data});
Ali Bahaari
  • 421
  • 2
  • 8