Commit 8357f464 authored by Mаартен - Maarten's avatar Mаартен - Maarten Committed by Joe Haddad

Update progressive enhancement example (#9507)

* no ssr component which uses useEffect hook

This library used wasn't updated for 4 years. I tried to contact the owner, which failed, and decided to create my own. So if you see this PR as a shameless plugin for my own component you can delete it. Just wanted to make this example more up to date.

* Update index.js

* fix linting

* Update index.js

* Update example
parent acf35179
......@@ -39,11 +39,18 @@ now
## The idea behind the example
Sometimes you want to **not** server render some parts of your application. That can be third party components without server render capabilities, components that depends on `window` and other browser only APIs or just because that content isn't important enough for the user (eg. below the fold content).
Sometimes you want to **not** server render some parts of your application.
In that case you can wrap the component in `react-no-ssr` which will only render the component client-side.
For example:
1. Third party components without server render capabilities
2. Components that depend on `window` or other browser only APIs
3. Content isn't important enough for the user (eg. below the fold content)
To handle these cases, you can conditionally render your component using the `useEffect` hook.
This example features:
- A custom hook called `useMounted`, implementing this behavior
- An app with a component that must only be rendered in the client
- A loading component that will be displayed before rendering the client-only component
......@@ -9,7 +9,6 @@
"dependencies": {
"next": "latest",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-no-ssr": "1.1.0"
"react-dom": "^16.7.0"
}
}
import React from 'react'
import NoSSR from 'react-no-ssr'
import React, { useEffect, useState } from 'react'
import Loading from '../components/Loading'
export default () => (
<main>
<section>
<h1>This section is server-side rendered.</h1>
</section>
function useMounted() {
const [mounted, setMounted] = useState(false)
useEffect(() => setMounted(true), [])
return mounted
}
<NoSSR onSSR={<Loading />}>
export default function HomePage() {
const isMounted = useMounted()
return (
<main>
<section>
<h2>
This section is <em>only</em> client-side rendered.
</h2>
<h1>This section is server-side rendered.</h1>
</section>
</NoSSR>
<style jsx>{`
section {
align-items: center;
display: flex;
height: 50vh;
justify-content: center;
}
`}</style>
</main>
)
{isMounted ? (
<section>
<h2>
This section is <em>only</em> client-side rendered.
</h2>
</section>
) : (
<Loading />
)}
<style jsx>{`
section {
align-items: center;
display: flex;
height: 50vh;
justify-content: center;
}
`}</style>
</main>
)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment