'"No routes matched location" error in React

I am creating a React app which can be used to manage company events. There are two components related to events that aren't working at the moment. These are the edit event component, and the event card component which displays all the information relevant to the event. I'm trying to pass the event ID in order to identify the relevant event to be edited or viewed. The useParams() hook is used to pass the ID. When I set up a route for the edit event feature and view event card feature, I get the following errors in the console.

The error shown in the edit event route is,

No routes matched location "/editEvent/(event ID)".

The error shown in the event card route is,

No routes matched location "/event/(event ID)"

The (event ID) contains the ID of the event that I'm trying to edit or view. The correct ID was visible in the address of the route.

I have attached the code of all components related to the edit event and event card features.

src/App.js

import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import AddProject from './Components/AddProject';
import AllProjects from './Components/AllProjects';
import AddEvents from './Components/AddEvents';
import AllEvents from './Components/AllEvents';
import EditProject from './Components/EditProject';
import ProjectDetails from './Components/ProjectDetails';
import EventCard from './Components/EventCard';
import EditEvent from './Components/EditEvent';
import { NoMatch } from './Components/NoMatch';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<AddProject />} />     
        <Route path="/allProjects" element={<AllProjects />} />
        <Route path="/addEvents/:projectName" element={<AddEvents />} />
        <Route path="/allEvents/:projectName" element={<AllEvents />} />
        <Route path="/editProject/:id" element={<EditProject />} />
        <Route Path="/project/:id" element={<ProjectDetails />} />
        <Route Path="/event/:id" element={<EventCard />} />
        <Route Path="/editEvent/:id" element={<EditEvent/>} />
        <Route Path='*' element={<NoMatch/>}></Route>
      </Routes>
    </Router>
  );
}

export default App;

src/Components/AllEvents.js

import { React, useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Button, Card } from 'react-bootstrap';
import axios from "axios";

function AllEvents() {
    const [listOfEvents, setListOfEvents] = useState([]);

    useEffect(() => {
        axios.get("/getEvent").then((response) => {
            setListOfEvents(response.data);
        })
    }, []);

    const { projectName } = useParams();

    const handleDelete = (_id) => {
        axios.delete(`/deleteEvent/${_id}`)
            .then((res) => {
                console.log(res);
                console.log(res.data);
            })

        const newList = listOfEvents.filter((event) => event._id !== _id);
        alert("Event was deleted");
        setListOfEvents(newList);
    }

    let navigate = useNavigate();

    const filteredList = listOfEvents.filter((event) => event.projectName === projectName);
    return (
        <div id="allEvents">
            <h1 style={{ textAlign: "center" }}>{projectName}</h1>
            <h3>All Events</h3>

            {filteredList.length > 0 ? (filteredList.map((events) => {
                return (
                    <div>
                        <Card className="detailsCard" border="dark">
                            <div className="details">
                                <span className="title">Event Name:</span>
                                <span className="data">{events.eventName}</span>
                            </div>
                            <div className="details">
                                <span className="title">Event Description:</span>
                                <span className="data">{events.eventDescription}</span>
                            </div>
                            <div className="details">
                                <span className="title">Event Start Date:</span>
                                <span className="data">{events.eventStartDate}</span>
                            </div>
                            <div className="details">
                                <span className="title">Event End Date:</span>
                                <span className="data">{events.eventEndDate}</span>
                            </div>
                            <div>
                                <Button variant="success" size="sm" type="submit" onClick={() => { navigate(`/event/${events._id}`) }}>View Event Card</Button>
                                <Button className="eventButton" variant="warning" size="sm" type="submit" onClick={() => { navigate(`/editEvent/${events._id}`) }}>Edit Event</Button>
                                <Button className="eventButton" variant="danger" size="sm" type="submit" onClick={() => { handleDelete(events._id) }}>Delete Event</Button>
                            </div>
                        </Card>
                    </div>
                );
            })
            ) : (
                <div>
                    <p>No events have been added yet</p>
                </div>
            )}

            <br />
            <Button variant="secondary" size="lg" onClick={() => { navigate(`/addEvents/${projectName}`) }}>Add new event</Button>
        </div>
    );
}

export default AllEvents;

src/Components/EditEvent.js

import { React, useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Form, Card, Button,CloseButton } from 'react-bootstrap';
import axios from "axios";

function EditEvent() {
    const [projectName, setProjectName] = useState();
    const [eventName, setEventName] = useState();
    const [eventDescription, setEventDescription] = useState();
    const [eventStartDate, setEventStartDate] = useState();
    const [eventEndDate, setEventEndDate] = useState();

    const { id } = useParams();

    let navigate = useNavigate();

    const editEvent = () => {
        axios.put(`/updateEvent/${id}`, {
            eventName,
            eventDescription,
            eventStartDate,
            eventEndDate
        }).then((res) => {
            alert("Project has been edited");
            console.log("Project edited");
        });
    }

    useEffect(() => {
        axios.get(`/getEvent/${id}`).then((res) => {
            setProjectName(res.data.events.projectName);
            setEventName(res.data.events.eventName);
            setEventDescription(res.data.events.eventDescription);
            setEventStartDate(res.data.events.eventStartDate);
            setEventEndDate(res.data.events.setEventEndDate);
            console.log(res.data.events);
        });
        // eslint-disable-next-line
    }, []);

    return (
        <div>
            <div className="eventCard">
                <Card border="dark" >
                    <Card.Header>
                        <div className="eventCardHeader">
                            Edit an Event
                            <CloseButton className="closeButton" onClick={() => { navigate(`/allEvents/${projectName}`) }} />
                        </div>
                    </Card.Header>
                    <Card.Body>
                        <Form>
                            <Form.Group>
                                <h5>Edit Event Name</h5>
                                <Form.Control as="textarea"
                                    rows={1}
                                    placeholder='Add Event Name'
                                    value={eventName}
                                    onChange={(event) => { setEventName(event.target.value) }}>
                                </Form.Control><br />
                            </Form.Group>

                            <Form.Group>
                                <h5>Edit Event Description</h5>
                                <Form.Control as="textarea"
                                    rows={3}
                                    placeholder='Add Event Description'
                                    value={eventDescription}
                                    onChange={(event) => { setEventDescription(event.target.value) }}>
                                </Form.Control><br />
                            </Form.Group>

                            <h5>Edit Event Duration</h5>

                            <Form.Label>Start Date</Form.Label><br />
                            <input
                                type="date"
                                min={new Date().toISOString().split('T')[0]}
                                max="2030-12-31"
                                value={eventStartDate}
                                onChange={(event) => { setEventStartDate(event.target.value) }} /><br />
                            <Form.Label>End Date</Form.Label><br />
                            <input
                                type="date"
                                min={new Date().toISOString().split('T')[0]}
                                max="2030-12-31"
                                value={eventEndDate}
                                onChange={(event) => { setEventEndDate(event.target.value) }} /><br />
                        </Form>
                        <Card.Footer style={{ paddingLeft: '50%' }}>
                            <Button variant="warning" size="lg" type="submit" onClick={editEvent}>Edit Project</Button>
                        </Card.Footer>

                    </Card.Body>
                </Card>

            </div>
        </div>
    );
}

export default EditEvent;

src/Components/EventCard.js

import { React, useEffect, useState } from "react";
import {  useParams, useNavigate } from "react-router-dom";
import axios from "axios";
import { CloseButton } from 'react-bootstrap';

 function EventCard(){
    const [eventName,setEventName] = useState();
    const [eventDescription,setEventDescription] = useState();
    const [eventStartDate,setEventStartDate] = useState();
    const [eventEndDate,setEventEndDate] = useState();

    const { id } = useParams();

    let navigate = useNavigate();

    useEffect(() =>{
        axios.get(`/getEvent/${id}`).then((res) => {
            console.log("Hello");
            setEventName(res.data.event.eventName);
            setEventDescription(res.data.event.eventDescription);
            setEventStartDate(res.data.event.eventStartDate);
            setEventEndDate(res.data.event.eventEndDate);
            console.log("EventData",res.data.event);
        });
    // eslint-disable-next-line
    },[]);

    return(
        <div>
            <CloseButton className="closeButton" onClick={() => { navigate("/allProjects") }} />
            {eventName}
            {eventDescription}
            {eventStartDate}
            {eventEndDate}
        </div>
    );  
 }

 export default EventCard;

routes/events.js

const express = require('express');
const router = express.Router();
const eventModel = require('../models/Events');

// Add an event
router.post("/createEvent", async (req, res) => {
    const event = req.body;
    const newEvent = new eventModel(event);
    await newEvent.save();

    res.json(event);
});

// Retrieve all events
router.get("/getEvent", (req, res) => {
    eventModel.find({}, (err, result) => {
        if (err) {
            res.json(err);
        } else {
            res.json(result);
        }
    });
});

// Retrieve a specific event
router.get("/getEvent/:id", (req,res) => {
    
    let eventId = req.params.id;

    eventModel.findById(eventId,(err,event) => {
        if(err){
            return res.status(400).json({success:false, err});
        }
        return res.status(200).json({
            success:true,
            event
        });
    });
});

// Update an event
router.put('/updateEvent/:id',(req,res) => {
    eventModel.findByIdAndUpdate(
        req.params.id,
        {
            $set:req.body
        },
        (err,updatedEvent) => {
            if(err){
                return res.status(400).json({error:err});
            }

            return res.status(200).json({
                success:"Updated succesfully"
            });
        }
    );
});

// Delete an event
router.delete('/deleteEvent/:id',(req,res) => {
    eventModel.findByIdAndRemove(req.params.id).exec((err,deletedEvent) => {
        if(err) return res.status(400).json({
            message:"Delete unsuccessful",err
        });

        return res.json({
            message:"Delete successful",deletedEvent
        });
    });
});


module.exports = router;

Server.js

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const cors = require('cors');

const projectRoutes = require('./routes/projects');
const eventRoutes = require('./routes/events');

app.use(express.json());
app.use(cors());

app.use(projectRoutes);
app.use(eventRoutes);

app.get("/", (req, res) => {
    res.send("Hello world");
}
);

//Actual url was removed when posting to stackoverflow
const DB_URL = '';

mongoose
.connect(DB_URL)
.then(() => {
    console.log('MongoDB connected');
})
.catch((err) => console.log('DB connection error',err));


app.listen(5000, () => console.log("Server is running in port 5000"));

I appreciate any help that I can get.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source