How do I redirect to another page on form submit?

Timothy

I'm trying to redirect to a certain page once I post my form but it doesn't redirect, it only posts the form data and does not redirect to the stated page

I've tried appending the && operator in order for onSubmit to do both functions but to no avail. I also tried having both "onSubmit" and "onClick" but it's only "onSubmit" that works

//./userspost.js
import React, { Component } from "react";
import { Redirect, Link } from "react-router-dom";
import Form1 from "./form1";
import { createUsers } from "./actions/appactions";

class userspost extends Component {
  state = {
    redirect: false
  };
  setRedirect = () => {
    this.setState({
      redirect: true
    });
  };
  renderRedirect = () => {
    if (this.state.redirect) {
      return <Redirect to="/users" />;
    }
  };
  handleSubmit(data) {
    console.log("form submission data", data);
    createUsers(data);
  }
  render() {
    return (
      <div>
        {this.renderRedirect()}
        <Form1 onSubmit={this.handleSubmit && this.setRedirect} />
      </div>
    );
  }
}

export default userspost;

for the posting the form data

//./form1.js
import React from "react";
import { Link } from "react-router-dom";
var createReactClass = require("create-react-class");
const Form1 = createReactClass({
  //setting initial state
  getInitialState() {
    return {
      firstName: this.props.firstName,
      lastName: this.props.lastName,
      userName: this.props.userName,
      role: this.props.role
    };
  },
  handleFirstChange(e) {
    this.setState({
      firstName: e.target.value
    });
  },
  handleLastChange(e) {
    this.setState({
      lastName: e.target.value
    });
  },
  handleUserChange(e) {
    this.setState({
      userName: e.target.value
    });
  },
  handleRoleChange(e) {
    this.setState({
      role: e.target.value
    });
  },
  handleSubmit(e) {
    e.preventDefault();
    this.props.onSubmit(this.state);
  },
  render() {
    return (
      <form
        name="categories_post"
        className="form-horizontal"
        onSubmit={this.handleSubmit}
      >
        <div id="categories_post">
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="firstName"
            >
              First Name
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.firstName}
                onChange={this.handleFirstChange}
                id="firstName"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="lastName"
            >
              Last Name
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.lastName}
                onChange={this.handleLastChange}
                id="lastName"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="userName"
            >
              UserName
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.userName}
                onChange={this.handleUserChange}
                id="userName"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="role">
              Role
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.role}
                onChange={this.handleRoleChange}
                id="role"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <div className="col-sm-2" />
            <div className="col-sm-10">
              <button
                type="submit"
                id="categoriesSubmit"
                className="btn-default btn"
              >
                submit
              </button>
            </div>
          </div>
          <div className="form-group">
            <div className="col-sm-2" />
            <div className="col-sm-10">
              <button className="btn btn-danger">
                <Link to="/users">Home</Link>
              </button>
            </div>
          </div>
        </div>
      </form>
    );
  }
});
export default Form1;

for posting using the fetch API

//./actions/appactions.js 
import fetch from "isomorphic-fetch";

export function createCategories(data) {
  return fetch("https://localhost:44341/api/categories", {
    method: "POST",
    mode: "cors",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(res => {
      return res;
    })
    .catch(err => err);
}
export function createUsers(data) {
  return fetch("https://localhost:44341/api/users/create", {
    method: "POST",
    mode: "cors",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(res => {
      return res;
    })
    .catch(err => err);
}
export function createBusiness(data) {
  return fetch("https://localhost:44341/api/businesslistings/create", {
    method: "POST",
    mode: "cors",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(res => {
      return res;
    })
    .catch(err => console.log(err));
}
k3llydev

The issue is that you are rendering the Redirect component along with the rest of your JSX everytime. Rendering only <Redirect to="" /> should solve your problem.

class userspost extends Component {
  state = {
    redirect: false
  };
  setRedirect = () => {
    this.setState({
      redirect: true
    });
  };
  handleSubmit(data) {
    console.log("form submission data", data);
    createUsers(data);
  }
  render() {

    if( this.state.redirect ){
       return <Redirect to="users/" />
    }

    return (
      <div>
        {this.renderRedirect()}
        <Form1 onSubmit={this.handleSubmit} />
      </div>
    );
  }
}

Also, use only the handleSubmit function in your form onSubmit event. Since adding two functions with && could cause unexpected results. And when everything is ready to redirect, just call your function setRedirect.

There is someone that already answered something similar, so I took a bit of help from there. Check it out:

https://stackoverflow.com/a/43230829/5568741

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I on Submit my Form redirect the Results to another Page in React

Redirect to another page after form submit

submit should not redirect to another page in HTML form

how do I redirect to another page?

How do I submit a form's data to another function without refreshing the page?

After submit the form how do I redirect to welcome component in React

How do I redirect my page on clicking submit?

How do I redirect to another page when a user successfully submits a form?

How can I have a button redirect to another page, but still be able to do form validation in HTML?

How do I submit the first form on a page with JavaScript?

React.js - How do I submit a form on page load?

How do I fill in and submit a form on another website with axios?

How to redirect to another page after click on submit button in form with required inputs

Django Ajax Form submit wrongly redirect to another page

How do I redirect to another page in a condition using php?

How do I raise PermissionDenied Redirect to another page using CBV?

How to submit a form results to a table on another page?

How to redirect to another view/page if the form is invalid

After submit redirect to another page

How to do a page slide transition on form submit?

How to stop redirect from partial page after form submit

how do I transfer data from a form to another page immediately?

How to open pop up modal when form submit sucessfully and hide pop after 2 mintues and redirect to another page in react js?

Submit form POST to another page but validate before redirect and keep on same page if validation fails

How do I limit access to a page only through redirect from another page

How do I change form data on submit?

How can i redirect after submit form React

How do I submit a PUT method form in Laravel without reloading the page?

Laravel 4 - How do I submit a form to add comments to a page with a URL variable?