0

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?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

1 Answers1

2

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";
mouafus
  • 148
  • 7
  • This is definitely the best approach but keep in mind that if you were not already using `react-router`, you would have to set up you're `routes` that symbolize you're pages. https://reactrouter.com/web/api/Switch – Hozeis Sep 23 '21 at 16:45
  • 1
    we can use window.location.href = "page url" in that case – mouafus Sep 23 '21 at 16:49