Hello folks! welcome back to a new section of our tutorial on Next.js. In this tutorial, we will be discussing about Next.js Imperative Routing.
So far we're using Link react component to navigate from one page to the other. There are also programmatic methods to achieve the same making use of Router component. Router component is usually used with html tags.
Update index.js file in pages directory using the following content -
So far we're using Link react component to navigate from one page to the other. There are also programmatic methods to achieve the same making use of Router component. Router component is usually used with html tags.
Update index.js file in pages directory using the following content -
import Router from 'next/router' import Head from 'next/head' function HomePage(props) { return ( <> <Head> <title>Welcome to Next.js!</title> </Head> <div>Welcome to Next.js!</div> <span onClick={() => Router.push('/posts/one')}>First Post</span> <br/> <div>Next stars: {props.stars}</div> <img src="/logo.png" alt="WebDesignTutorialz Logo" /> </> ) } export async function getServerSideProps(context) { const res = await fetch('https://api.github.com/repos/vercel/next.js') const json = await res.json() return { props: { stars: json.stargazers_count } } } export default HomePage
Start Next.js Server
Run the following command below to start the server -
npm run dev > nextjs@1.0.0 dev \Node\nextjs > next ready - started server on http://localhost:3000 event - compiled successfully event - build page: / wait - compiling... event - compiled successfully event - build page: /next/dist/pages/_error wait - compiling... event - compiled successfully
Output
Open localhost:3000 in any browser of your choice to see the following result -
Click on First Post which is not a link but is clickable.
READ: Next.js | Routing
Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we are going to be studying about Next.js Shallow Routing.
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.