-
Notifications
You must be signed in to change notification settings - Fork 2
Users, sharing data and layout
We've been creating pages, but sometime you need / want common elements:
- UI: Navbar, footer, etc
- Data: information shared on many pages (ex: user name)
We're using React Router - it allows you to nest pages - ie to have one main page with common elements (navbar, footer), and "child" pages.

Let's try that out:
const router = createBrowserRouter([ { path: "/", element: <App />, errorElement: <Error />, children: [ { path: "/mycomics", element: <MyComicsPage /> }, { path: "/addcomic", element: <NewComicPage /> }, ], }, ]);
Moving our pages under the App one means App page is always going to be shown. We can update the App page to include our Navbar - navigation will still show the content of App.
The special "Outlet" component means "show the child page here".
What if we want a page showing at "/"? How can we define a "Home"?
A component that takes 100% of the width, background yellow with links for each page (and a logo, ...)
We use NavLink for the linking.
But... we don't have a user - let's fake it for now.
- We want to maintain state at the level it's needed - generally as "down" as possible
- But here our user could be needed in the whole app - let's have App maintain it (user/setUser)
How can we pass data to child components in React?
Props. Props can be values... but also functions!
We can pass user/setUser to our NavBar... but what about this "Outlet"
React has a build in feature to share values to a whole subtree of components - it's called a Context.