简体   繁体   中英

How to route to another react component using button in react-router-dom v6

I'm completely new to react and got stuck on the following 'route' part. Here is the code:

This is my ListEmployeeComponent:

import React, { Component } from 'react';
import EmployeeService from '../services/EmployeeService';

class ListEmployeesComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            employees: []
        }
        this.addEmployee = this.addEmployee.bind(this);
    }

    componentDidMount() {
        EmployeeService.getEmployees().then((res) => {
            this.setState({employees: res.data});
        });
    }

    addEmployee() {
        this.props.history.push('add-employee');
    }

    render() {
        return (
            <div>
                <h2 className="text-center">Employee List</h2>
                <div className="row">
                    <button className="btn btn-primary" onClick={this.addEmployee}>Add Employee</button>
                </div>
                <div className="row">
                    <table className="table table-striped table-bordered">
                        
                        <thead>
                            <tr>
                                <th>Id</th>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Email Id</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        
                        <tbody>
                            {
                                this.state.employees.map(
                                    employee =>
                                    <tr key={employee.id}>
                                        <td>{employee.id}</td>
                                        <td>{employee.firstName}</td>
                                        <td>{employee.lastName}</td>
                                        <td>{employee.email}</td>
                                    </tr>
                                )
                            }
                        </tbody>
                    </table>
                </div>
            </div>
        );
    }
}

export default ListEmployeesComponent;

And this is my App.js:

import './App.css';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom'
import FooterComponent from './components/FooterComponent';
import HeaderComponent from './components/HeaderComponent';
import ListEmployeesComponent from './components/ListEmployeesComponent';
import CreateEmployeeComponent from './components/CreateEmployeeComponent';

function App() {
  return (
    <div>
      <Router>
        <HeaderComponent/>
        <div className="container">
          <Routes>
            <Route path="/" element={<ListEmployeesComponent/>}></Route>
            <Route path="/home" element={<ListEmployeesComponent/>}></Route>
            <Route path="/add-employee" element={<CreateEmployeeComponent/>}></Route>
          </Routes>
        </div>
        <FooterComponent/>
      </Router>
    </div>
  )
}

export default App;

My issue is that I want to route to CreateEmployeeComponent when the button gets clicked, but there is no action happening when I click the button. I tried checking the new documentation for react-router v6 but it wasn't much help. What can I do differently here to resolve my issue?

Solution 1:

You can wrap the button in ListEmployeeComponent using Link from react-router-dom.

<Link to="/add-employee">
   <button className="btn btn-primary">Add Employee</button>
</Link>

reference: react-router-dom

Solution 2:

history in react-router-dom v6 has been replaced by Navigate. So if you want to push /add-employee to history you need to use <Navigate to='/add-employee' push={true}/>

Make following changes in your ListEmployeeComponent.js:

add a state in your constructor:

constructor(props) {
    super(props);
    this.state = {
        navigate: false,
        employees: []
    }
    this.addEmployee = this.addEmployee.bind(this);
}

change your function:

addEmployee() {
   this.props.history.push('add-employee');
}

to

addEmployee() {
  this.setState({
    navigate: true,
  });
}

and change your render method to:

  render() {
    const { navigate } = this.state;
    if (navigate) {
      return <Navigate to="/add-employee" push={true} />;
    }

    return (
      <div>
        <h2 className="text-center">Employee List</h2>
        <div className="row">
        ........
        //rest of the code
  }

reference: react-router-dom-v6 doc

First you have to import link in ListEmployeeComponent and have to use button tags between link tags and you have to add [to="/add-employee"] attributes to link tag

code: import {Link} from "react-router-dom"

Add Employee

I guess your issue will be solve by this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM