Why we need to do this in every single component over and over again to use history to navigate our app?
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
I expect to access history object in every single component.
CodePudding user response:
You could try using the 1st Example: Basic Routing section from the guide in the references below if you just need to navigate to a page. After setting it up, you could rewrite your HomeButton function as follows:
import { Link } from "react-router-dom";
function HomeButton() {
return (
<Link to="/home">
Go home
</Link>
);
}
You can also put your useHistory code in a file which requires a property and call it from anywhere in your application. From your HomeButtom function, you would call it with the property, “/home”. References:
1st Example: Basic Routing. React Training / React Router. https://reactrouter.com/web/guides/quick-start. (Accessed 1 October, 2021).
CodePudding user response:
I think you can use custom hook to reduce the code.
import { useHistory } from "react-router-dom";
const useHomeClickHandle = () => {
let history = useHistory();
// you should use useCallback here to avoid rerender
function handleClick() {
history.push("/home");
}
return handleClick
}
function HomeButton() {
const handleClick = useHomeHandleClick()
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
// OR
function HomeButton() {
// if you don't have any conditional control here
return (
<button type="button" onClick={useHomeHandleClick()}>
Go home
</button>
);
}