Nextjs6 with Apollo Graphql and Material-UI Tutorial
Step 1 - Yarn installation
There are two options how to install Yarn. The first option is to use npm:
Another option is to go to the official download page and get the installer for your operating system and run it.
The other method would be to go to the official download page and get the installer for your operating system and run it.
Step 2 - Project initialization
To start, create a sample project by running the following commands:
mkdir github-client
cd github-client
yarn init
yarn add react react-dom prop-types next
mkdir pages
Then open the "package.json" in the github-client directory and add the following script.
{
"scripts": {
"dev": "next"
}
}
Everything is ready. To start the dev server, you need to run the following command:
When you run localhost:3000 you will see this page:

Step 3 - Babel Installation
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in old browsers or environments.
To install babel compiler core use command:
Babel module resolver
A Babel plugin to add a new resolver for your modules when compiling your code using Babel. This plugin allows you to add new "root" directories that contain your modules. It also allows you to setup a custom alias for directories, specific files, or even other npm modules.
Let's install babel module resolver.
yarn add babel-plugin-module-resolver -D
After that we need to update .babelrc config. So we can import dependencies without declaring related path.
.babelrc
"plugins": [
["module-resolver", {
"root": ["./"],
"alias": {
"components": "./components",
"containers": "./containers",
"queries": "./graphql/queries"
}
}]
]
This allows us to make this:
import { Home } from 'components';
Instead of this:
import { Home } from '../../components';
Step 4 Linters configuration
To avoid big refactoring in the future, you need to integrate linters to your app. For that, add eslint as development dependency:
You need a wrapper for babel’s parser used for eslint. Use yarn to install package:
Babel-eslint allows you to lint ALL valid Babel code
There are few dependencies that you have to install.
This package provides Airbnb's .eslintrc as an extensible shared config.
yarn add eslint-config-airbnb -D
Install ESLint plugin with rules that help validate proper imports.
yarn add eslint-plugin-import -D
Install Static AST checker for accessibility rules on JSX elements.
yarn add eslint-plugin-jsx-a11y -D
Install eslint plugin for React.
yarn add eslint-plugin-react -D
Initialize eslint config.
We're going to use airbnb eslint config.
Choose the following settings:
How would you like to configure ESLint? Use a popular style guide
Which style guide do you want to follow? Airbnb
Do you use React? Yes
What format do you want your config file to be in? JSON
Would you like to install them now with npm? No
Now we have .eslintrc.json with the following configuration
We're going to use .js extensions instead of .jsx because JSX is not standard JS, and is not likely to ever be. So we explicitly add this option to the .eslintc.json:
{
"parser": "babel-eslint",
"rules": {
"react/jsx-filename-extension": ["error", { "extensions": [".js", ".jsx"] }]
},
"extends": "airbnb"
}
Step 5 - Material UI integration
In a nutshell, Material-UI is an open-source project that features React components that implement Google’s Material Design.
It kick-started in 2014, not long after React came out to the public, and has grown in popularity ever since. With over 35,000 stars on GitHub, Material-UI is one of the top user interface libraries for React out there.
There are few additional steps that we need to apply before start using material with NextJS framework
First of all install some additional packages.
Install JSS:
JSS is a more powerful abstraction than CSS. It uses JavaScript as a language to describe styles in a declarative and maintainable way. It is a high performance JS to CSS compiler which works at runtime and server-side.
Install react-jss:
We use React-JSS because it provides components for JSS as a layer of abstraction and has the following range of benefits compared to lower level core:
- Theming support.
- Critical CSS extraction.
- Lazy evaluation - sheet is created only when the component will mount.
- Auto attach/detach - sheet will be rendered to the DOM when the component is about to mount, and will be removed when no element needs it.
- A Style Sheet gets shared between all elements.
- Function values and rules are updated automatically with props.
Install styled-jsx package for server-side rendering:
Styled-jsx is a full, scoped and component-friendly CSS support for JSX (rendered on the server or the client).
Install material core with icons
yarn add @material-ui/core @material-ui/icons
@material-ui/core is a set of react components that implement Google's Material Design.
@materail-ui/icons is a set of components with svg icons
There is an example app that shows how to properly integrate material-ui specifically for nextjs framework. https://github.com/mui-org/material-ui/tree/master/examples/nextjs
Now create lib/getPageContext.js
/* eslint-disable no-underscore-dangle */
import { SheetsRegistry } from 'jss';
import { createMuiTheme, createGenerateClassName } from '@material-ui/core/styles';
// A theme with custom primary and secondary color.
// It's optional.
const theme = createMuiTheme();
function createPageContext() {
return {
theme,
// This is needed in order to deduplicate the injection of CSS in the page.
sheetsManager: new Map(),
// This is needed in order to inject the critical CSS.
sheetsRegistry: new SheetsRegistry(),
// The standard class name generator.
generateClassName: createGenerateClassName(),
};
}
export default function getPageContext() {
// Make sure to create a new context for every server-side request so that data
// isn't shared between connections (which would be bad).
if (!process.browser) {
return createPageContext();
}
// Reuse context on the client-side.
if (!global.__INIT_MATERIAL_UI__) {
global.__INIT_MATERIAL_UI__ = createPageContext();
}
return global.__INIT_MATERIAL_UI__;
}
Next.js uses the App component to initialize pages. You can override it and control the page initialization. Which allows you to do amazing things like:
- Persisting layout between page changes
- Keeping state when navigating pages
- Custom error handling using componentDidCatch
- Inject additional data into pages (for example by processing GraphQL queries)
To override, create the ./pages/_app.js file and override the App class as shown below:
import React from 'react';
import App, { Container } from 'next/app';
import { MuiThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import JssProvider from 'react-jss/lib/JssProvider';
import getPageContext from '../lib/getPageContext';
class MainApp extends App {
constructor(props) {
super(props);
this.pageContext = getPageContext();
}
pageContext = null;
componentDidMount() {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles && jssStyles.parentNode) {
jssStyles.parentNode.removeChild(jssStyles);
}
}
render() {
const { Component, pageProps } = this.props;
return (
<Container>
{/* Wrap every page in Jss and Theme providers */}
<JssProvider
registry={this.pageContext.sheetsRegistry}
generateClassName={this.pageContext.generateClassName}
>
{/* MuiThemeProvider makes the theme available down the React
tree thanks to React context. */}
<MuiThemeProvider
theme={this.pageContext.theme}
sheetsManager={this.pageContext.sheetsManager}
>
{/*
CssBaseline kickstart an elegant, consistent, and simple baseline to build upon.
*/}
<CssBaseline />
{/*
Pass pageContext to the _document though the renderPage enhancer to render collected styles on server side.
*/}
<Component pageContext={this.pageContext} {...pageProps} />
</MuiThemeProvider>
</JssProvider>
</Container>
);
}
}
export default MainApp;
You need to add this line to .eslintrc.json to avoid document is not defined error:
Pages in Next.js skip the definition of the surrounding document's markup. For example, you never include <html>