In this short lesson, instead of hard-coded Hi, user
, let's show the actual logged-in user.
To show the user, we will use the same concept of sharing data by adding it to the HandleInertiaRequests
Middleware. Let's pass only the name and email.
app/Http/Middleware/HandleInertiaRequests.php:
class HandleInertiaRequests extends Middleware{ // ... public function share(Request $request): array { return array_merge(parent::share($request), [ 'flash' => [ 'message' => fn () => $request->session()->get('message') ], 'user' => [ 'name' => $request->user()?->name, 'email' => $request->user()?->email, ], ]); }}
Now, we can access these values using the usePage().props
.
resources/js/Layouts/AppLayout.jsx:
import { Link, usePage } from '@inertiajs/react'; export default function AppLayout({ children }) { const { flash, user } = usePage().props; return ( // ... <div className="flex items-center"> <div className="flex flex-col"> <div>Hi, user</div> <div>email</div> <div>Hi, {user.name}</div> <div>{user.email}</div> </div> </div> // ... );}
This was a short lesson on passing the parameters to any React component without defining them as props.