Categories
discuss

Redirect with React Functional Components

I am in need of help, I am coding this form and after I submit it, the state for “posted” changes from false to true and I would expect “return Redirect to=”/landing” ;” to redirect me to the landing …

I am in need of help, I am coding this form and after I submit it, the state for “posted” changes from false to true and I would expect “return Redirect to=”/landing” ;” to redirect me to the landing page, however, it doesn’t which I assume is because the line doesn’t re-run after the initial render. I was hoping that changing the state of “posted” would cause a re-render. I have heard about using history push and tried to adapt it to my code yet I failed. I don’t know how to wrap my component with “withRouter” given that I have it already wrapped with “connect”. How can I achieve this? I have read numerous posts about this yet I can’t figure how to adapt it to my code. Any help is appreciated.

import React, { useState } from "react";
import Navbar from "./Navbar";
import { connect, useDispatch } from "react-redux";
import { Redirect } from "react-router-dom";
import { createProject } from "../actions/projectAction";
import PropTypes from "prop-types";
import { push } from "connected-react-router";

const EditProject = ({ posted, createProject }) => {
  const dispatch = useDispatch();
  const [formData, setFormData] = useState({
    projectTitle: "",
    projectDescription: "",
    deliveryDate: ""
  });

  const { projectTitle, projectDescription, deliveryDate } = formData;

  const onChange = e => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const onSubmit = async e => {
    e.preventDefault();
    createProject({ projectTitle, projectDescription, deliveryDate });
    dispatch(push("/login"));
  };

  if (posted) {
    return <Redirect to="/landing" />;
  }

  return (
    <div>
      <Navbar />
      <div className="container">
        <form onSubmit={e => onSubmit(e)}>
          <h4>Project Title</h4>
          <input
            name="projectTitle"
            value={projectTitle}
            className="form-control"
            placeholder="Your project title"
            onChange={e => onChange(e)}
          />
          <h4>Delivery Date</h4>
          <input
            type="date"
            className="form-control"
            name="deliveryDate"
            value={deliveryDate}
            onChange={e => onChange(e)}
          />
          <h4>Description</h4>
          <textarea
            name="projectDescription"
            value={projectDescription}
            className="form-control"
            rows="10"
            onChange={e => onChange(e)}
          ></textarea>
          <input type="submit" className="btn btn-primary" value="Create" />
          <a href="/projects" className="btn btn-danger">
            Cancel
          </a>
        </form>
      </div>
    </div>
  );
};

EditProject.propTypes = {
  createProject: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  posted: state.posted
});

export default connect(mapStateToProps, { createProject })(EditProject);

Answer

I think you have to define your route. From my following code you can get a little bit idea of the routing.

In App.js basically I defined the routes and I have created two more functional components Landing and EditProject to simulate your idea. Moreover I have used Link for navigation purpose

App.js

import React, { Component } from "react";
import { BrowserRouter, Route, Switch, Link } from "react-router-dom";
import EditProject from "./editProject";
import Landing from "./landing";

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div id="container">
          <div>
            <Link to="/">Landing Page</Link>
            <Link to="/editproject">Edit Project</Link>
          </div>
          <Switch>
            <Route path="/editproject" component={EditProject} />
            <Route exact path="/" component={Landing} />
          </Switch>
        </div>
      </BrowserRouter>
    );
  }
}

export default App;

Landing functional component

import React from "react";

const Landing = () => {
  return <h1>Landing Page</h1>;
};

export default Landing;

EditProject functional component

import React from "react";

const EditProject = props => {
  function handleSubmit(e) {
    e.preventDefault();
    console.log("submitted");
    //do your task here before redirect
    //...
    props.history.push("/");
  }

  return (
    <div>
      <h1>Edit Project</h1>
      <form onSubmit={handleSubmit}>
        <button>Submit</button>
      </form>
    </div>
  );
};

export default EditProject;

Hope it will help you.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..