1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Fix coding style of snippets (#2806)

This commit is contained in:
Brikou CARRE 2017-09-08 23:22:59 +02:00 committed by Tim Neutkens
parent 8b507a7943
commit c0d031d90e

315
readme.md
View file

@ -77,9 +77,7 @@ After that, the file-system is the main API. Every `.js` file becomes a route th
Populate `./pages/index.js` inside your project:
```jsx
export default () => (
<div>Welcome to next.js!</div>
)
export default () => <div>Welcome to next.js!</div>
```
and then just run `npm run dev` and go to `http://localhost:3000`. To use another port, you can run `npm run dev -- -p <your port here>`.
@ -99,9 +97,11 @@ Every `import` you declare gets bundled and served with each page. That means pa
```jsx
import cowsay from 'cowsay-browser'
export default () => (
<pre>{ cowsay.say({ text: 'hi there!' }) }</pre>
)
export default () =>
<pre>
{cowsay.say({ text: 'hi there!' })}
</pre>
```
### CSS
@ -116,7 +116,7 @@ export default () => (
We bundle [styled-jsx](https://github.com/zeit/styled-jsx) to provide support for isolated scoped CSS. The aim is to support "shadow CSS" similar to Web Components, which unfortunately [do not support server-rendering and are JS-only](https://github.com/w3c/webcomponents/issues/71).
```jsx
export default () => (
export default () =>
<div>
Hello world
<p>scoped!</p>
@ -139,7 +139,6 @@ export default () => (
}
`}</style>
</div>
)
```
Please see the [styled-jsx documentation](https://www.npmjs.com/package/styled-jsx) for more examples.
@ -156,9 +155,7 @@ Please see the [styled-jsx documentation](https://www.npmjs.com/package/styled-j
It's possible to use any existing CSS-in-JS solution. The simplest one is inline styles:
```jsx
export default () => (
<p style={{ color: 'red' }}>hi there</p>
)
export default () => <p style={{ color: 'red' }}>hi there</p>
```
To use more sophisticated CSS-in-JS solutions, you typically have to implement style flushing for server-side rendering. We enable this by allowing you to define your own [custom `<Document>`](#user-content-custom-document) component that wraps each page
@ -168,9 +165,7 @@ To use more sophisticated CSS-in-JS solutions, you typically have to implement s
Create a folder called `static` in your project root directory. From your code you can then reference those files with `/static/` URLs:
```jsx
export default () => (
<img src="/static/my-image.png" />
)
export default () => <img src="/static/my-image.png" />
```
### Populating `<head>`
@ -187,7 +182,8 @@ We expose a built-in component for appending elements to the `<head>` of the pag
```jsx
import Head from 'next/head'
export default () => (
export default () =>
<div>
<Head>
<title>My page title</title>
@ -195,7 +191,6 @@ export default () => (
</Head>
<p>Hello world!</p>
</div>
)
```
_Note: The contents of `<head>` get cleared upon unmounting the component, so make sure each page completely defines what it needs in `<head>`, without making assumptions about what other pages added_
@ -211,16 +206,19 @@ When you need state, lifecycle hooks or **initial data population** you can expo
```jsx
import React from 'react'
export default class extends React.Component {
static async getInitialProps ({ req }) {
return req
? { userAgent: req.headers['user-agent'] }
: { userAgent: navigator.userAgent }
static async getInitialProps({ req }) {
const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
return { userAgent }
}
render () {
return <div>
Hello World {this.props.userAgent}
</div>
render() {
return (
<div>
Hello World {this.props.userAgent}
</div>
)
}
}
```
@ -241,7 +239,10 @@ _Note: `getInitialProps` can **not** be used in children components. Only in `pa
You can also define the `getInitialProps` lifecycle method for stateless components:
```jsx
const Page = ({ stars }) => <div>Next stars: {stars}</div>
const Page = ({ stars }) =>
<div>
Next stars: {stars}
</div>
Page.getInitialProps = async ({ req }) => {
const res = await fetch('https://api.github.com/repos/zeit/next.js')
@ -278,16 +279,20 @@ Client-side transitions between routes can be enabled via a `<Link>` component.
```jsx
// pages/index.js
import Link from 'next/link'
export default () => (
<div>Click <Link href="/about"><a>here</a></Link> to read more</div>
)
export default () =>
<div>
Click{' '}
<Link href="/about">
<a>here</a>
</Link>{' '}
to read more
</div>
```
```jsx
// pages/about.js
export default () => (
<p>Welcome to About!</p>
)
export default () => <p>Welcome to About!</p>
```
__Note: use [`<Link prefetch>`](#prefetching-pages) for maximum performance, to link and prefetch in the background at the same time__
@ -322,9 +327,15 @@ The component `<Link>` can also receive an URL object and it will automatically
```jsx
// pages/index.js
import Link from 'next/link'
export default () => (
<div>Click <Link href={{ pathname: '/about', query: { name: 'Zeit' }}}><a>here</a></Link> to read more</div>
)
export default () =>
<div>
Click{' '}
<Link href={{ pathname: '/about', query: { name: 'Zeit' } }}>
<a>here</a>
</Link>{' '}
to read more
</div>
```
That will generate the URL string `/about?name=Zeit`, you can use every property as defined in the [Node.js URL module documentation](https://nodejs.org/api/url.html#url_url_strings_and_url_objects).
@ -336,9 +347,15 @@ The default behaviour for the `<Link>` component is to `push` a new url into the
```jsx
// pages/index.js
import Link from 'next/link'
export default () => (
<div>Click <Link href='/about' replace><a>here</a></Link> to read more</div>
)
export default () =>
<div>
Click{' '}
<Link href="/about" replace>
<a>here</a>
</Link>{' '}
to read more
</div>
```
##### Using a component that support `onClick`
@ -348,24 +365,30 @@ export default () => (
```jsx
// pages/index.js
import Link from 'next/link'
export default () => (
<div>Click <Link href='/about'><img src="/static/image.png" /></Link></div>
)
export default () =>
<div>
Click{' '}
<Link href="/about">
<img src="/static/image.png" />
</Link>
</div>
```
##### Forcing the Link to expose `href` to its child
##### Forcing the Link to expose `href` to its child
If child is an `<a>` tag and doesn't have a href attribute we specify it so that the repetition is not needed by the user. However, sometimes, youll want to pass an `<a>` tag inside of a wrapper and the `Link` wont recognize it as a *hyperlink*, and, consequently, wont transfer its `href` to the child. In cases like that, you should define a boolean `passHref` property to the `Link`, forcing it to expose its `href` property to the child.
```jsx
import Link from 'next/link'
import Unexpected_A from 'third-library'
export default ({ href, name }) => (
<Link href={ href } passHref>
<Unexpected_A>{ name }</Unexpected_A>
export default ({ href, name }) =>
<Link href={href} passHref>
<Unexpected_A>
{name}
</Unexpected_A>
</Link>
)
```
#### Imperatively
@ -383,9 +406,10 @@ You can also do client-side page transitions using the `next/router`
```jsx
import Router from 'next/router'
export default () => (
<div>Click <span onClick={() => Router.push('/about')}>here</span> to read more</div>
)
export default () =>
<div>
Click <span onClick={() => Router.push('/about')}>here</span> to read more
</div>
```
Above `Router` object comes with the following API:
@ -407,14 +431,16 @@ You can use an URL object the same way you use it in a `<Link>` component to `pu
```jsx
import Router from 'next/router'
const handler = () => Router.push({
pathname: '/about',
query: { name: 'Zeit' }
})
const handler = () =>
Router.push({
pathname: '/about',
query: { name: 'Zeit' }
})
export default () => (
<div>Click <span onClick={handler}>here</span> to read more</div>
)
export default () =>
<div>
Click <span onClick={handler}>here</span> to read more
</div>
```
This uses of the same exact parameters as in the `<Link>` component.
@ -435,7 +461,7 @@ Here's a list of supported events:
Here's how to properly listen to the router event `routeChangeStart`:
```js
Router.onRouteChangeStart = (url) => {
Router.onRouteChangeStart = url => {
console.log('App is changing to: ', url)
}
```
@ -461,7 +487,7 @@ If you change a route while in between a new deployment, we can't navigate the a
But you can customize that via `Route.onAppUpdated` event like this:
```js
Router.onAppUpdated = (nextUrl) => {
Router.onAppUpdated = nextUrl => {
// persist the local state
location.href = nextUrl
}
@ -480,7 +506,7 @@ Shallow routing allows you to change the URL without running `getInitialProps`.
You can do this by invoking either `Router.push` or `Router.replace` with the `shallow: true` option. Here's an example:
```jsx
```js
// Current URL is "/"
const href = '/?counter=10'
const as = href
@ -491,7 +517,7 @@ Now, the URL is updated to `/?counter=10`. You can see the updated URL with `thi
You can watch for URL changes via [`componentWillReceiveProps`](https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops) hook as shown below:
```jsx
```js
componentWillReceiveProps(nextProps) {
const { pathname, query } = nextProps.url
// fetch data based on the new query
@ -566,15 +592,26 @@ You can add `prefetch` prop to any `<Link>` and Next.js will prefetch those page
import Link from 'next/link'
// example header component
export default () => (
export default () =>
<nav>
<ul>
<li><Link prefetch href='/'><a>Home</a></Link></li>
<li><Link prefetch href='/about'><a>About</a></Link></li>
<li><Link prefetch href='/contact'><a>Contact</a></Link></li>
<li>
<Link prefetch href="/">
<a>Home</a>
</Link>
</li>
<li>
<Link prefetch href="/about">
<a>About</a>
</Link>
</li>
<li>
<Link prefetch href="/contact">
<a>Contact</a>
</Link>
</li>
</ul>
</nav>
)
```
#### Imperatively
@ -583,17 +620,15 @@ Most prefetching needs are addressed by `<Link />`, but we also expose an impera
```jsx
import Router from 'next/router'
export default ({ url }) => (
export default ({ url }) =>
<div>
<a onClick={ () => setTimeout(() => url.pushTo('/dynamic'), 100) }>
<a onClick={() => setTimeout(() => url.pushTo('/dynamic'), 100)}>
A route transition will happen after 100ms
</a>
{
// but we can prefetch it!
Router.prefetch('/dynamic')
}
{// but we can prefetch it!
Router.prefetch('/dynamic')}
</div>
)
```
### Custom server and routing
@ -637,8 +672,7 @@ app.prepare().then(() => {
} else {
handle(req, res, parsedUrl)
}
})
.listen(3000, (err) => {
}).listen(3000, err => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
@ -676,64 +710,63 @@ Here are a few ways to use dynamic imports.
#### 1. Basic Usage (Also does SSR)
```js
```jsx
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(import('../components/hello'))
export default () => (
export default () =>
<div>
<Header />
<DynamicComponent />
<p>HOME PAGE is here!</p>
</div>
)
```
#### 2. With Custom Loading Component
```js
```jsx
import dynamic from 'next/dynamic'
const DynamicComponentWithCustomLoading = dynamic(
import('../components/hello2'),
{
loading: () => (<p>...</p>)
loading: () => <p>...</p>
}
)
export default () => (
export default () =>
<div>
<Header />
<DynamicComponentWithCustomLoading />
<p>HOME PAGE is here!</p>
</div>
)
```
#### 3. With No SSR
```js
```jsx
import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(
import('../components/hello3'),
{ ssr: false }
)
export default () => (
const DynamicComponentWithNoSSR = dynamic(import('../components/hello3'), {
ssr: false
})
export default () =>
<div>
<Header />
<DynamicComponentWithNoSSR />
<p>HOME PAGE is here!</p>
</div>
)
```
#### 4. With Multiple Modules At Once
```js
```jsx
import dynamic from 'next/dynamic'
const HelloBundle = dynamic({
modules: (props) => {
modules: props => {
const components = {
Hello1: import('../components/hello1'),
Hello2: import('../components/hello2')
@ -743,18 +776,17 @@ const HelloBundle = dynamic({
return components
},
render: (props, { Hello1, Hello2 }) => (
render: (props, { Hello1, Hello2 }) =>
<div>
<h1>{props.title}</h1>
<h1>
{props.title}
</h1>
<Hello1 />
<Hello2 />
</div>
)
})
export default () => (
<HelloBundle title="Dynamic Bundle"/>
)
export default () => <HelloBundle title="Dynamic Bundle" />
```
### Custom `<Document>`
@ -773,24 +805,24 @@ import Document, { Head, Main, NextScript } from 'next/document'
import flush from 'styled-jsx/server'
export default class MyDocument extends Document {
static getInitialProps ({ renderPage }) {
const {html, head, errorHtml, chunks} = renderPage()
static getInitialProps({ renderPage }) {
const { html, head, errorHtml, chunks } = renderPage()
const styles = flush()
return { html, head, errorHtml, chunks, styles }
}
render () {
render() {
return (
<html>
<Head>
<style>{`body { margin: 0 } /* custom! */`}</style>
</Head>
<body className="custom_class">
{this.props.customValue}
<Main />
<NextScript />
</body>
</html>
<html>
<Head>
<style>{`body { margin: 0 } /* custom! */`}</style>
</Head>
<body className="custom_class">
{this.props.customValue}
<Main />
<NextScript />
</body>
</html>
)
}
}
@ -808,19 +840,22 @@ __Note: React-components outside of `<Main />` will not be initialised by the br
```jsx
import React from 'react'
export default class Error extends React.Component {
static getInitialProps ({ res, jsonPageRes }) {
const statusCode = res ? res.statusCode : (jsonPageRes ? jsonPageRes.status : null)
static getInitialProps({ res, jsonPageRes }) {
const statusCode = res
? res.statusCode
: jsonPageRes ? jsonPageRes.status : null
return { statusCode }
}
render () {
render() {
return (
<p>{
this.props.statusCode
? `An error ${this.props.statusCode} occurred on server`
: 'An error occurred on client'
}</p>
<p>
{this.props.statusCode
? `An error ${this.props.statusCode} occurred on server`
: 'An error occurred on client'}
</p>
)
}
}
@ -836,20 +871,23 @@ import Error from 'next/error'
import fetch from 'isomorphic-fetch'
export default class Page extends React.Component {
static async getInitialProps () {
static async getInitialProps() {
const res = await fetch('https://api.github.com/repos/zeit/next.js')
const statusCode = res.statusCode > 200 ? res.statusCode : false
const json = await res.json()
return { statusCode, stars: json.stargazers_count }
}
render () {
if(this.props.statusCode) {
return <Error statusCode={this.props.statusCode} />
render() {
if (this.props.statusCode) {
return <Error statusCode={this.props.statusCode} />
}
return (
<div>Next stars: {this.props.stars}</div>
<div>
Next stars: {this.props.stars}
</div>
)
}
}
@ -863,7 +901,7 @@ For custom advanced behavior of Next.js, you can create a `next.config.js` in th
Note: `next.config.js` is a regular Node.js module, not a JSON file. It gets used by the Next server and build phases, and not included in the browser build.
```javascript
```js
// next.config.js
module.exports = {
/* config options here */
@ -874,7 +912,7 @@ module.exports = {
You can specify a name to use for a custom build directory. For example, the following config will create a `build` folder instead of a `.next` folder. If no configuration is specified then next will create a `.next` folder.
```javascript
```js
// next.config.js
module.exports = {
distDir: 'build'
@ -902,7 +940,7 @@ module.exports = {
// Important: return the modified config
return config
},
webpackDevMiddleware: (config) => {
webpackDevMiddleware: config => {
// Perform customizations to webpack dev middleware config
// Important: return the modified config
@ -928,12 +966,9 @@ This is designed so that you are not surprised by modifications we could make to
Here's an example `.babelrc` file:
```js
```json
{
"presets": [
"next/babel",
"stage-0"
],
"presets": ["next/babel", "stage-0"]
}
```
@ -998,15 +1033,15 @@ Simply develop your app as you normally do with Next.js. Then create a custom Ne
```js
// next.config.js
module.exports = {
exportPathMap: function () {
exportPathMap: function() {
return {
"/": { page: "/" },
"/about": { page: "/about" },
"/p/hello-nextjs": { page: "/post", query: { title: "hello-nextjs" } },
"/p/learn-nextjs": { page: "/post", query: { title: "learn-nextjs" } },
"/p/deploy-nextjs": { page: "/post", query: { title: "deploy-nextjs" } }
'/': { page: '/' },
'/about': { page: '/about' },
'/p/hello-nextjs': { page: '/post', query: { title: 'hello-nextjs' } },
'/p/learn-nextjs': { page: '/post', query: { title: 'learn-nextjs' } },
'/p/deploy-nextjs': { page: '/post', query: { title: 'deploy-nextjs' } }
}
},
}
}
```
@ -1023,9 +1058,9 @@ For that you may need to add a NPM script to `package.json` like this:
```json
{
"scripts": {
"build": "next build && next export"
}
"scripts": {
"build": "next build && next export"
}
}
```