Skip to content

Commit e3c2c77

Browse files
docs: add Class components tutorial (#1784)
1 parent 718f253 commit e3c2c77

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

www/docs/tutorials.md

+4
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@ This approach can be used to authenticate existing user accounts against any bac
4343

4444
How to write tests using Cypress.
4545

46+
### [Usage with class components](tutorials/usage-with-class-components)
47+
48+
How to use `useSession()` hook with class components.
49+
4650
## Other tutorials and explainers
4751

4852
_These are tutorials and explainers that have been submitted or that we have found on the web and are hosted elsewhere They include articles, videos and example projects. Submissions for inclusion are welcome!_
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
id: usage-with-class-components
3+
title: Usage with class components
4+
---
5+
6+
If you want to use the `useSession()` hook in your class components you can do so with the help of a higher order component or with a render prop.
7+
8+
## Higher Order Component
9+
10+
```js
11+
import { useSession } from "next-auth/client"
12+
13+
const withSession = Component => props => {
14+
const [session, loading] = useSession()
15+
16+
// if the component has a render property, we are good
17+
if (Component.prototype.render) {
18+
return <Component session={session} loading={loading} {...props} />
19+
}
20+
21+
// if the passed component is a function component, there is no need for this wrapper
22+
throw new Error([
23+
"You passed a function component, `withSession` is not needed.",
24+
"You can `useSession` directly in your component."
25+
].join("\n"))
26+
};
27+
28+
// Usage
29+
class ClassComponent extends React.Component {
30+
render() {
31+
const {session, loading} = this.props
32+
return null
33+
}
34+
}
35+
36+
const ClassComponentWithSession = withSession(ClassComponent)
37+
```
38+
39+
## Render Prop
40+
41+
```js
42+
import { useSession } from "next-auth/client"
43+
44+
const UseSession = ({ children }) => {
45+
const [session, loading] = useSession()
46+
return children({ session, loading })
47+
};
48+
49+
// Usage
50+
class ClassComponent extends React.Component {
51+
render() {
52+
return (
53+
<UseSession>
54+
{({ session, loading }) => (
55+
<pre>{JSON.stringify(session, null, 2)}</pre>
56+
)}
57+
</UseSession>
58+
)
59+
}
60+
}
61+
```

0 commit comments

Comments
 (0)