|
| 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