mirror of
https://github.com/zhigang1992/react.git
synced 2026-02-06 17:19:02 +08:00
97 lines
2.0 KiB
Plaintext
97 lines
2.0 KiB
Plaintext
import Layout from 'lib/components/layout'
|
|
import { Code, Link, Text, Spacer, Note } from 'components'
|
|
|
|
export const meta = {
|
|
title: 'Server Render',
|
|
description: 'description',
|
|
index: 15,
|
|
}
|
|
|
|
|
|
## Server Render
|
|
|
|
### ZEIT-UI React on the Server
|
|
|
|
All Components of `@zeit-ui/react` are compatible with **Server Render**. In fact, the document you see now is rendered by the server.
|
|
|
|
<Note>If you deploy by static files, you can skip this section.</Note>
|
|
|
|
<Spacer y={3} />
|
|
|
|
### Next.js
|
|
|
|
In `next.js` framework, you need customization file `_document.js`,
|
|
please refer to <Link href="https://nextjs.org/docs/advanced-features/custom-document" rel="nofollow">Next.js document here</Link>
|
|
to create file `_document.js`.
|
|
|
|
Then we add the following codes to the file:
|
|
|
|
```js
|
|
import Document, { Html, Head, Main, NextScript } from 'next/document'
|
|
import { CSSBaseline } from '@zeit-ui/react'
|
|
|
|
class MyDocument extends Document {
|
|
static async getInitialProps (ctx) {
|
|
const initialProps = await Document.getInitialProps(ctx)
|
|
const styles = CSSBaseline.flush()
|
|
|
|
return {
|
|
...initialProps,
|
|
styles: (
|
|
<>
|
|
{initialProps.styles}
|
|
{styles}
|
|
</>
|
|
)
|
|
}
|
|
}
|
|
|
|
render() { ... }
|
|
}
|
|
```
|
|
|
|
Here's an examples that might help you: <Link href="https://github.com/unix/unix.bio/blob/template/pages/_document.jsx" rel="nofollow">_document.jsx</Link>.
|
|
|
|
<Spacer y={3} />
|
|
|
|
### Custom Server
|
|
|
|
In the custom server, also get the style set from function `CSSBaseLine.flush`.
|
|
|
|
```js
|
|
import React from 'react'
|
|
import ReactDOM from 'react-dom/server'
|
|
import { CSSBaseLine } from 'zeit-ui/react'
|
|
import App from './app'
|
|
|
|
export default (req, res) => {
|
|
const app = ReactDOM.renderToString(<App />)
|
|
const styles = CSSBaseLine.flush()
|
|
const html = ReactDOM.renderToStaticMarkup(<html>
|
|
<head>{ styles }</head>
|
|
<body>
|
|
<div id="root" dangerouslySetInnerHTML={{__html: app}} />
|
|
</body>
|
|
</html>)
|
|
res.end('<!doctype html>' + html)
|
|
}
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export default ({ children }) => <Layout meta={meta}>{children}</Layout>
|