Home > Back-end >  this.props.history.push('/') IS NOT WORKING in CLASS Component
this.props.history.push('/') IS NOT WORKING in CLASS Component

Time:01-15

Please help me to resolve the issue of this.props.history.push('/') IS NOT WORKING in CLASS Component. As we do not have any scope of using history anymore. Unable to implement navigate. Please do help. Same issue with props.location.state.contact.

**const { name, email } = props.location.state.contact;**
import React, { Component } from "react";
import "../assets/css/AddContact.css";
import { Navigate } from "react-router-dom";
import { v4 as uuid } from "uuid";

class AddContact extends Component {
  state = {
    id: uuid(),
    name: "",
    email: "",
  };

 
  add = (e) => {
    e.preventDefault();
    if (this.state.name === "" || this.state.email === "") {
      alert("All fields are required!");
      return;
    }
    this.props.addContactHandler(this.state);
    this.setState({ name: "", email: "" });
    this.props.history.push("/");
  };

  render() {
    return (
      <div className="contactForm">
        <h2 className="contactForm__title">Add Contact</h2>
        <div className="contactForm__form">
          <form action="/" method="post" onSubmit={this.add}>
            <div className="contactForm__nameField">
              <label htmlFor="name">Name</label>
              <br />
              <input
                type="text"
                placeholder="Enter your name"
                name="name"
                id="name"
                value={this.state.name}
                onChange={(e) => this.setState({ name: e.target.value })}
              />
            </div>
            <div className="contactForm__emailField">
              <label htmlFor="email">Email</label>
              <br />
              <input
                type="email"
                placeholder="Enter your email"
                name="email"
                id="email"
                value={this.state.email}
                onChange={(e) => this.setState({ email: e.target.value })}
              />
            </div>
            <button className="contactForm__button">Add</button>
          </form>
        </div>
      </div>
    );
  }
}

export default AddContact;

I tried out from all of my references.

CodePudding user response:

You need to use the withRouter Higher Order Component provided with the React Router library in order to get access to those props (history and location automatically).

So just import that, and change your export to

export default withRouter(AddContact);

[Note that this assumes you are using React Router v5 or before - there is no withRouter in v6 which is the latest version. But your use of a class component implies that you are using an earlier version - v6 only works well if you use function components, as withRouter has been replaced with Hooks.]

  • Related