'<Link to=> not switching pages
I've been working on this dropdown menu for a while but I can't seem to get the dropdown menu to change the page I'm on and I don't understand what's wrong with it I am really new to ReactJs, I have a module called DropDownMenu it is calling DropDownItem and when DropDownItem is clicked is called a function called handle click but in the HandleClick it is not switching the page to the current Props.Route clicked on and i don't know enough of whats going on to really figure it out
import React from "react";
import { Link } from "react-router-dom";
function DropdownItem(props) {
const handleClick = () => {
<Link to={props.route}></Link>;
console.log(props.route);
};
return (
<a href="#" className="menu-item" onClick={handleClick}>
<span className="icon-button">{props.leftIcon}</span>
<span className="Route">{props.route}</span>
{props.children}
<span className="icon-right">{props.rightIcon}</span>
</a>
);
}
export default DropdownItem;
Solution 1:[1]
You can't just throw a <Link> in the middle of a callback function and expect it to do anything when called.
Use the <Link> element instead of the <a> element.
Make use of useNavigate if you need to trigger navigation from a callback (which you don't in this case).
Solution 2:[2]
You can use useHistory hook.you may use to navigate.
when you use react router dom v5
import { useHistory } from "react-router-dom";
let history = useHistory();
const handleClick = () => {
history.push(`/${props.route}`);
console.log(props.route);
};
when you use react router dom v5
import { useHistory } from "react-router-dom";
const navigate = useNavigate();
const handleClick = () => {
navigate(`../${props.route}`, { replace: true });
console.log(props.route);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin |
| Solution 2 |
