Home > Net >  navigate with react-router-dom v6 not working
navigate with react-router-dom v6 not working

Time:04-30

1. client/src/components/App.js

import React from "react";
import { Routes, Route, useNavigate } from "react-router-dom";
import Home from "./Home";
import Blocks from "./Blocks";
import ConductTransaction from "./ConductTransaction";
import TransactionPool from "./TransactionPool";
const App = () => {
  const navigate = useNavigate();
  return (
    <Routes>
      <Route exact path="/" element={<Home />} />
      <Route exact path="/blocks" element={<Blocks />} />
      <Route
        exact
        path="/conduct-transaction"
        element={<ConductTransaction navigate={navigate} />}
      />
      <Route exact path="/transaction-pool" element={<TransactionPool />} />
    </Routes>
  );
};
export default App;

2. client/src/components/ConductTransaction.js

import React, { Component } from "react";
import { Link } from "react-router-dom";
class ConductTransaction extends Component {
  state = { recipient: "", amount: 0 };
  updateRecipient = (event) => {
    event.preventDefault();
    this.setState({ recipient: event.target.value });
  };
  updateAmount = (event) => {
    event.preventDefault();
    this.setState({ amount: Number(event.target.value) });
  };
  conductTransaction = () => {
    const { recipient, amount, success } = this.state;
    fetch("http://localhost:3000/api/transact", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ recipient, amount }),
    })
      .then((response) => response.json())
      .then((json) => {
        alert(json.message || json.type);
        this.props.navigate("/transaction-pool");
      });
  };
  render() {
    return (
      <div className="ConductTransaction">
        <Link to="/">Go to Home</Link>
        <h3>Conduct a Transaction</h3>
        <form onSubmit={this.conductTransaction}>
          <div className="FormGroup">
            <label>Recipient Address:</label>
            <input
              type="text"
              placeholder="Recipient account"
              value={this.state.recipient}
              onChange={this.updateRecipient}
            />
          </div>
          <div className="FormGroup">
            <label>Amount:</label>
            <input
              type="number"
              placeholder="Amount"
              value={this.state.amount}
              onChange={this.updateAmount}
            />
          </div>
          <br />
          <button className="ShowMoreBtn" type="submit">
            Transact
          </button>
        </form>
      </div>
    );
  }
}
export default ConductTransaction;

3. client/index.js

import React from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./components/App";
import "./index.css";
const container = document.getElementById("root");
const root = createRoot(container);
root.render(<BrowserRouter><App /></BrowserRouter>);

After conductTransaction() and closing the alert(), the page just refreshes (and adds an interrogation sign at the end of the url) instead of going to the "/transaction-pool" page.

Using:

  • "react-router-dom": "^6.3.0",

CodePudding user response:

Only issue I see is where the code isn't preventing the default form action from occurring, which will reload your entire app.

conductTransaction = (submitEvent) => { // <-- name the onSubmit event
  submitEvent.preventDefault();         // <-- prevent the default form action
  const { recipient, amount, success } = this.state;
  fetch("http://localhost:3000/api/transact", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ recipient, amount }),
  })
    .then((response) => response.json())
    .then((json) => {
      alert(json.message || json.type);
      this.props.navigate("/transaction-pool");
    });
};
  • Related