We can create server-side rendered React apps and static sites easily Next.js.
In this article, we’ll take a look at how to get started with Next.js.
Getting Started
We can create our Next.js project with its provided command-line program.
To create the project, we just run:
npx create-next-app
or:
yarn create next-app
to create our project.
Then to start the dev server, we run:
npm run dev
Then we go to http://localhost:3000/ and our app.
Now we can create a component in the pages
folder to add our page.
We go into the pages
folder, create an hello.js
file and add:
function Hello() {
return <div>hello world</div>
}
export default Hello
to it.
We’ve to remember to export the component so that it’ll be rendered.
Then we can go to http://localhost:3000/hello and see our page.
Next.js does routing automatically by the file name so we don’t have to worry about that.
Pages with Dynamic Routes
If we want to create pages with dynamic routes, we just put them in the folder structure and the URLs will follow the same structure.
For example, we can create a posts
folder and create our files.
We create 1.js
in pages/posts
and write:
function Hello() {
return <div>hello 1</div>
}
export default Hello
Likewise, we create 2.js
in the same folder and write:
function Hello() {
return <div>hello 2</div>
}
export default Hello
Then when we go to http://localhost:3000/posts/1 and http://localhost:3000/posts/2, we’ll see hello 1
and hello 2
respectively.
Pre-rendering
Next.js pre-renders every page by default.
The HTML for each page are created in advanced.
This is better for performance and SEO than rendering it on the client-side.
The pages only come with the JavaScript it needs to load so that it loads faster.
There’re 2 forms of pre-rendering.
One is static generation and the other is server-side rendering.
Static generation means that HTML is generated at build time and are reused on each request.
Since it reuses the pages, it’ll be the fastest way to render pages, so this is the recommended option.
The other option is server-side rendering, which renders the HTML no each request.
We can choose between the 2 types of rendering.
Static Generation with Data
We can generate pages statically with data.
To do this, we can write:
pages/yesno.js
function YesNo({ data }) {
return <p>{data.answer}</p>
}
export async function getStaticProps() {
const res = await fetch('https://yesno.wtf/api')
const data = await res.json()
return {
props: {
data,
},
}
}
export default YesNo
We created a new component file with the YesNo
component.
The getStaticProps
function gets the data asynchronously from an API.
Then we return the resolved value by return an object with the data
in the props
property.
Then we can get that data from the props in the YesNo
component.
And in the JSX, we displayed the data.
Conclusion
We can create pages with Next.js that displays static content or content from an API easily.