Skip to content

Next.js

Marie-Louise edited this page Jan 23, 2019 · 37 revisions

Learning Next.js using this tutorial :

Getting started with Next.js

Navigation

To achieve client-side routing, use the <link>component which is part of the Link API. It's necessary to import next/link as Link. see the example below

// This is the Link API
import Link from 'next/link'

const Index = () => (
  <div>
    <Link href="/about">
      <a>About Page</a>
    </Link>
   <p>Hello Next.js</p>
 </div>
)

export default Index

Link must be used within a div like any other component . However, there is one requirement for components placed inside a Link is that they should accept onClick prop.

Client-Side History Support

when you click back, usually this is handled by next/link instead of being handled in the usual way location.history

Styling a Link

add the rule between {{ and }}. Check the example below

a style={{ fontSize: 20 }}

<Link href="/about">
  <a style={{ fontSize: 20 }}>About Page</a>
</Link>

Shared components

<Header />

<layout>

Creating a component

the example below is an component with two links

import Link from 'next/link'

const linkStyle = {
  marginRight: 15
}

const ComponentName = () => (
    <div>
        <Link href="/">
          <a style={linkStyle}>Home</a>
        </Link>
        <Link href="/about">
          <a style={linkStyle}>About</a>
        </Link>
    </div>
)

export default ComponentName

the component must be imported in order to be used in the site. So in the index.js add the necessary code:

import ComponentName from '../components/ComponentName'

export default () => (
  <div>
    <ComponentName />
    <p>Hello Next.js</p>
  </div>
)

Higher Order Component (HOC)

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.

Concretely, a higher-order component is a function that takes a component and returns a new component

Query Parameters

The example below shows a URL with a query param at the end. It starts from ? the name is p and the value is 1

http://example.com/foo?p=1

the format of a query parameter is below

name=value or in the case of the example p=1. The example below has a second query parameter. The first one is separated by using the ? and the second using &.

Query parameters are separate from the path in the sense that they can perform or have an effect on things like caching etc. but they are included in the whole URL when the server makes a request.

http://example.com/foo?p=1&g=neat

Clone this wiki locally