0

Based on the example source code from Inertiajs (https://inertiajs.com/shared-data#accessing-shared-data), we can use usePage() hook to get the props that passing from server-side

import { usePage } from '@inertiajs/react'

export default function Layout({ children }) {
  const { auth } = usePage().props

  return (
    <main>
      <header>
        You are logged in as: {auth.user.name}
      </header>
      <content>
        {children}
      </content>
    </main>
  )
}

My question is how can we get the data (come from the server-side) inside the Class Component? Or what is the replacement for the usePage() hook in the Class Component?

Han Tran
  • 2,073
  • 4
  • 22
  • 37

1 Answers1

0

What is the Inertiajs usePage() equally in React Class Component

usePage() is a custom hook provided by Inertiajs to make the possibility of accessing server-side shared data. so this has nothing to do with functional or class component

the real question is how to use a hook inside a class component

You can't use Hooks inside a class component. However, you can use HOC (Higher-Order Components) pattern to use hook logic inside existing class component.

take a look at this answer

Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38
  • `usePage() is a custom hook provided by Inertiajs` so my question is does Inertiajs has the same thing (officially) that can be used inside a class component or not? – Han Tran Mar 19 '23 at 22:24
  • No the package works with hooks, but you still can use HOC pattern to use hook logic inside existing class component, and I gave you the link to how to do it – Ahmed Sbai Mar 19 '23 at 22:38
  • did you manage how to make it work with class component or should I update my answer show you how ? – Ahmed Sbai Mar 20 '23 at 13:09
  • I don't want to do the workaround in order to use the usePage() hook with HOC. What I want to archive is has the same result with Class Component but with official support, if Inertiajs does not support getting the shared data from Class Component then I instead convert my component to a Functional one. – Han Tran Mar 20 '23 at 15:23
  • yeah there is no other way either you work with FC or use a HOC and I recommand using FC classes component are no longer supported if you want to advance in React you have to work with FC but note that using HOC is not against react rules or Inertiajs rules :) – Ahmed Sbai Mar 20 '23 at 15:27