So youāve tried Create React App, and maybe youāre thinking, āSure, itās nice and all, but what if I want code splitting, universal architecture, and a powerful router with zero configuration cost?ā If so youāre in luck.
Enter Next.js from the next-level engineers at Zeit, a dead simple boilerplate for hitting the ground running with some of Reactās most desireable features, tax free.
Start things off the usual way, namely by making a directory for your project and initializing it with a package.json
. Youāll want to add the following scripts to that file:
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
}
Now go ahead and add a few directories: pages
, static
, and components
.
That last oneās not strictly required, but itāll come in handy momentarily. šæ
$ npm install next --save
And thatās it. Youāre configured with all the bells and whistles. Letās dig into how it works.
The first thing to note is that every .js
file in the pages
directory will be routed automatically ā index.js
routes to /
; bite.js
routes to /bite
; and so on. This is also where your code splitting happens, with each discrete page getting a discrete bundle complete with scoped dependencies and server rendering where applicable.
Next uses a CDN to leverage the browserās cache for efficiency in serving React. š It has a local fallback and can be turned off.
We could leave it there, and things would be cool as they stand, but wait, thereās more.
import Link from 'next/link';
...
<Link href={`about?story=${assets.story}`}>About This Site</Link>
And therein lies your lazy-loading. Use Nextās Link
component where applicable and the machinery beneath will take it from there. Furthermore, the astute observer would take note of that query string on the href
, and that astute eye would be rewarded. Clicked Link
s receive a prop called url
, on which the query
can be accessed.
This is a fine moment to revisit that components
directory. With pages doing all this heavy lifting youāll want a place to stow your more modular odds and ends to keep your routing clean.
Another cool trick up Nextās sleeve is this bad boy:
import React from 'react';
import Head from 'next/head';
export default ({title}) => {
return <Head>
<title>{title}</title>
<link rel="stylesheet" href="static/styles.css" />
</Head>
}
The Head
component allows you to dynamically reconfigure the document head. Mighty useful.
import React from 'react';
import css from 'next/css';
let p = css({
color: '#858576',
fontSize: 32
});
export default ({caption}) => <p {...p}>{caption}</p>
Similarly useful is the teamās inclusion of the Glamor inline CSS module. The old ways work, too, all the way to vanilla objects and require
statements, but itās a nice touch.
ā ļøļø Itās worth noting that Next is approaching a major release (2.x.x) that will change aspects of its API and that the readme on Github is out of sync with the version youāre installing via npm (^1.2.3).
And for our final trick, letās bring it all together with a little data fetching. Next.js holds out getInitialProps
in all its async/await
glory for your data gathering needs but makes no prescriptions for what other tools you use. All that really matters is you use something equally suited to the browser and the server since itāll run on both.
import React from 'react';
import axios from 'axios';
export default class extends React.Component {
static async getInitialProps () {
const res = await axios.get('https://api.npmjs.org/downloads/point/last-week/next');
return {nextNpmDownloads: res.data.downloads};
}
render () {
return <div>
{`Did you know Next has had ${this.props.nextNpmDownloads} on npm in the last month?`}
</div>
}
}
All that remains is to fire up your dev server care of npm run dev
, point your browser to port 3000, and say hello to simplicity in its most sophisticated form.
š If you think thatās cool, wait till we deploy it.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the āreport an issueā button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.