so this is my code:
import Router from "next/router";
import React from "react";
export default function MainIndex() {
return (<React.Fragment>
<h1>Main Index Page</h1>
<button onClick={() => Router.push('/family')}>Family</button>
<button onClick={() => Router.push('/dynamic-id-page')}>Dynamic-id-page</button><br /><br />
<button onClick={() => Router.push('/fav-games')}>World Of WarCraft</button>
</React.Fragment>);
}
My question is: How can I create a function so I can use it as a callback for different routes.
CodePudding user response:
You should use "useRouter" :
import {useRouter} from "next/router"
then
export default function MainIndex() {
const router = useRouter();
const navigate = (event) => (url) => router.push(url)
...}
Then
<button onClick={navigate("/family")}> Family </button>
But keep in mind that this kind of "optimization" isn't really one... The inline function in your original code is easier to understand and premature optimization is the root of all evil