Skip to content

Users, sharing data and layout

Martin Van Aken edited this page Sep 15, 2024 · 1 revision

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)

Nesting pages

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.

image

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

Creating a NavBar

A component that takes 100% of the width, background yellow with links for each page (and a logo, ...)

We use NavLink for the linking.

Showing the user

But... we don't have a user - let's fake it for now.

Sharing user info with the whole application

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

React has a build in feature to share values to a whole subtree of components - it's called a Context.

Clone this wiki locally