How to Redirect After Form Submission in React Router?

Estimated read time 2 min read

In React Router, you can redirect to a new page after a form submission using the Redirect component. Here’s an example of how to redirect after form submission in React Router:

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

function MyComponent() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    email: ""
  });

  const handleSubmit = (event) => {
    event.preventDefault();
    // do something with form data
    setIsSubmitted(true);
  };

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevState) => ({
      ...prevState,
      [name]: value
    }));
  };

  if (isSubmitted) {
    return <Redirect to="/success" />;
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name:</label>
      <input
        type="text"
        id="name"
        name="name"
        value={formData.name}
        onChange={handleChange}
      />
      <label htmlFor="email">Email:</label>
      <input
        type="email"
        id="email"
        name="email"
        value={formData.email}
        onChange={handleChange}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

In this example, we’re defining a form with two input fields and a “Submit” button. We’re using state variables to track whether the form has been submitted (isSubmitted) and the form data (formData). When the form is submitted, the handleSubmit function is called, which sets the isSubmitted state variable to true to trigger the redirect.

We’re using the Redirect component from React Router to redirect to a new page with the to prop set to the path of the success page. We’re also using a conditional statement to check if the form has been submitted, and only rendering the form if the isSubmitted state variable is false.

Note that in order to use the Redirect component, your component must be rendered as a child of a Router component, such as a BrowserRouter or HashRouter. This allows React Router to update the URL and render the appropriate components based on the current route.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply