Home > Web Front-end > JS Tutorial > body text

How to Resolve \'TypeError: Cannot Read Properties of Undefined (reading \'push\')\' When Attempting to Redirect in React Router v6?

Linda Hamilton
Release: 2024-10-30 14:55:03
Original
908 people have browsed it

How to Resolve

Navigating Programmatically with React Router v6: Resolving TypeError

Problem

Encountering the error message "TypeError: Cannot read properties of undefined (reading 'push')" when attempting to redirect after a user action, such as clicking a submit button. This indicates that the navigate prop used for the redirection is undefined.

Solution

1. Convert to a Function Component

Use the useNavigate hook for navigation within a function component. This hook is only compatible with function components.

2. Create a Custom HOC for Class Components

Custom withRouter HOC:

const withRouter = WrappedComponent => props => {
  const navigate = useNavigate();
  // etc... other react-router-dom v6 hooks

  return (
    <WrappedComponent
      {...props}
      navigate={navigate}
      // etc...
    />
  );
};
Copy after login

Decorate the Class Component:

export default withRouter(AddContacts);
Copy after login

3. Use the Navigate Function

Use the navigate function for navigation instead of the history object used in previous versions of React Router. The syntax has changed to:

this.props.navigate("/path");
Copy after login

Complete working code for AddContacts.js:

import React, { Component } from "react";
import { Consumer } from "../../context";
import TextInputGroup from "../layout/TextInputGroup";
import { v4 as uuidv4 } from "uuid";
import withRouter from "./withRouter"; // Custom HOC

class AddContacts extends Component {
  state = {
    name: "",
    email: "",
    phone: "",
    errors: {},
  };

  onSubmit = (dispatch, e) => {
    e.preventDefault();

    const { name, email, phone } = this.state;

    //Check for errors

    if (name === "") {
      this.setState({ errors: { name: "Name is required" } });
      return;
    }
    if (email === "") {
      this.setState({ errors: { email: "Email is required" } });
      return;
    }
    if (phone === "") {
      this.setState({ errors: { phone: "Phone is required" } });
      return;
    }

    const newContact = {
      id: uuidv4(),
      name,
      email,
      phone,
    };
    dispatch({ type: "ADD_CONTACT", payload: newContact });

    this.setState({
      name: "",
      email: "",
      phone: "",
      errors: {},
    });
    this.props.navigate("/"); // Navigate using custom HOC
  };

  onChange = (e) => this.setState({ [e.target.name]: e.target.value });
  render() {
    const { name, email, phone, errors } = this.state;

    return (
      <Consumer>
        {(value) => {
          const { dispatch } = value;

          return (
            <div className="card mb-3">
              <div className="card-header">Add Contacts</div>
              <div className="card-body">
                <form onSubmit={this.onSubmit.bind(this, dispatch)}>
                  <TextInputGroup
                    label="Name"
                    name="name"
                    placeholder="Enter Name..."
                    value={name}
                    onChange={this.onChange}
                    error={errors.name}
                  />
                  <TextInputGroup
                    label="Email"
                    name="email"
                    type="email"
                    placeholder="Enter Email..."
                    value={email}
                    onChange={this.onChange}
                    error={errors.email}
                  />
                  <TextInputGroup
                    label="Phone"
                    name="phone"
                    placeholder="Enter Phone..."
                    value={phone}
                    onChange={this.onChange}
                    error={errors.phone}
                  />
                  <input
                    type="submit"
                    value="Add Contact"
                    className="btn btn-light btn-block mt-3"
                  />
                </form>
              </div>
            </div>
          );
        }}
      </Consumer>
    );
  }
}

export default withRouter(AddContacts); // Export wrapped component
Copy after login

This solution allows for navigation from class components in React Router v6, despite the initial error indicating an undefined navigation prop.

The above is the detailed content of How to Resolve \'TypeError: Cannot Read Properties of Undefined (reading \'push\')\' When Attempting to Redirect in React Router v6?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!