Search code examples
javascriptreactjsjsxreact-router-domreact-props

React Router: Unable to Navigate to a Route Using useNavigate Hook


I am currently working on a React application that uses React Router for navigation. I have a component called ShowNotes where I want to implement a "Delete" button that navigates to the "/DeleteNotes" route when clicked. However, I'm encountering an issue where the navigation is not working as expected.

Here are the details of the problem:

  • I've confirmed that my routing setup is correct, with routes defined for both "/ShowNotes" and "/DeleteNotes".

  • I'm using the useNavigate hook from react-router-dom to handle navigation.

  • When I click the "Delete" button in the ShowNotes component, nothing happens; the expected navigation does not occur.

I've tried the following troubleshooting steps:

  1. Ensured the routing configuration is accurate.

  2. Verified that the useNavigate hook is functioning as expected.

  3. Checked the browser console for any errors (none were found).

  4. Confirmed that the "DeleteNotes" component and route are correctly set up.

  5. Checked for conflicting event handlers or CSS issues that might interfere with the button click.

Despite these efforts, I still can't get the navigation to work as intended. Can someone please provide guidance on how to resolve this issue? Any insights or suggestions would be greatly appreciated.

ShowNotes

import axios from 'axios';
import React, { useEffect, useState } from 'react'
import Spinner from '../components/Spinner';
import Button from '../components/Button';
import BackButton from '../components/BackButton';
import { useNavigate } from 'react-router-dom';

function ShowNotes() {
  const navigate = useNavigate();
    const [notes, setNotes] = useState([]);
    const [loading, setLoading] = useState(false);
    const handleDelete = () => {
      navigate('/');
    };
    
    useEffect(() => {
      setLoading(true);
      axios
        .get('http://localhost:3000/notes')
        .then((res) => {
          setNotes(res.data.notes);
          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
        });
    }, []);
console.log(notes);
  return (
    <div>
        {loading ? (
        <Spinner/>
      ) : (
      <div className="container mx-auto mt-4">
        <BackButton/>

        <h1 className="flex justify-center text-3xl font-bold mb-4">OUR NOTES</h1>
        <table className="w-full table-auto">
          <thead>
            <tr>
              <th className="px-4 py-2">ID</th>
              <th className="px-4 py-2">TITLE</th>
              <th className="px-4 py-2">BODY</th>
              <th className="px-4 py-2">Actions</th>
            </tr>
          </thead>
          <tbody>
            {notes.map((item,index) => (
              <tr key={item._id}>
                <td className="border px-4 py-2">{index+1}</td>
                <td className="border px-4 py-2">{item.title}</td>
                <td className="border px-4 py-2">{item.body}</td>
                <td className="border px-4 py-2">
                <div className="flex justify-center">
                  <Button color="red-500" hoverColor="red-700" name="Delete" onClick={()=>handleDelete()} />
                  <Button color="blue-500" hoverColor="blue-700" name="Add" />
                  <Button color="purple-500" hoverColor="purple-700" name="Edit"/>
                  <Button color="green-500" hoverColor="green-700" name="Show"/>
                </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>)}
    </div>
  )
}

export default ShowNotes

This is the Button component (maybe it cause the problem)

function Button(props) {
  const buttonClassName = `bg-${props.color} hover:bg-${props.hoverColor} text-white font-bold py-2 px-4 rounded mr-2`;

  return (
    <button className={buttonClassName}>
      {props.name}
    </button>
  );
}

export default Button;

Solution

  • You need to pass the onClick prop through to the button element.

    <Button
      color="red-500"
      hoverColor="red-700"
      name="Delete"
      onClick={handleDelete} // <-- onClick prop passed
    />
    
    function Button(props) {
      const buttonClassName = `bg-${props.color} hover:bg-${props.hoverColor} text-white font-bold py-2 px-4 rounded mr-2`;
    
      return (
        <button
          className={buttonClassName}
          onClick={props.onClick} // <-- pass onClick handler to button
        >
          {props.name}
        </button>
      );
    }
    
    export default Button;