Search code examples
javascriptreactjsmaterial-uireact-typescript

Redirect users after form submit


I have this example for a React form with Typescript and Material-UI.

import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
import { Box, Button, Container, Grid, Typography } from "@material-ui/core";
import SaveIcon from "@material-ui/icons/Save";
import { TicketDTO } from "../../service/support/types";
import { postTicket } from "../../service/support";
import { useForm } from "react-hook-form";
import { Redirect } from "react-router-dom";

export default function OpenTicket(props: any) {

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<TicketDTO>();

  const onSubmit = async (data: TicketDTO) => {
    postTicket(data)
      .then(({ data }) => {
        console.log(data.title);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const formHandler = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    console.log(e.target);
  };

  return (
    <Container>
          <form onSubmit={handleSubmit(onSubmit)}>
              <TextField
                id="title"
                {...register("title", {
                  required: true,
                  maxLength: 40,
                })}
              />

              <Button
                  variant="contained"
                  color="primary"
                  size="small"
                  type="submit"
                  startIcon={<SaveIcon />}
              >
                Submit Ticket
              </Button>
          </form>
    </Container>
  );
}

After I successfully submit the form how I can redirect the user to a new page?


Solution

  • You can do this

     const router = useHistory();
    const onSubmit = async (data: TicketDTO) => {
        postTicket(data)
            .then(({ data }) => {
                console.log(data.title);
                router.push('/path_name_of_the_page')
            })
            .catch((err) => {
                console.log(err);
            });
    };
    

    note that useHistory() are imported form 'react-router'

    import {useHistory} from "react-router";