Home > Software design >  Passing props to <Outlet /> when nestining routes in React Router v6?
Passing props to <Outlet /> when nestining routes in React Router v6?

Time:11-19

How can I pass props to the <Outlet /> component when I am nestin routes?

// Parrent Comp 
{
  const [format, setFormat] = useState('rgb');
  const color = [hex, rgb, rgba]
  
  // ...

  return (
    <PaletteNavBar changeFormat={setFormat}/>

      {colorId ? <ColorBoxes /> : <Outlet color={color[format]} />}

      // setFormat(hex) is called down here
    <PaletteFooter />;
  )
}

I don't want to pass them via URL parameters.

CodePudding user response:

The Outlet doesn't take any props, nor will it pass anything on to what it renders. It is simply an output for children routes of a component.

Pass them to the component rendered by the Route, it's the Route that is rendered into the Outlet.

Example:

const Layout = () => (
  <div className="super-style">
    <h1>My super awesome layout container</h1>
    <Outlet /> // <-- children routes rendered here
  </div>
);

...

<Routes>
  <Route element={<Layout />}>
    <Route // <-- rendered into Outlet of Layout
      path="..."
      element={<Component foo="bar" />} // <-- pass props to component here
    />
  </Route>
  ... other routes for outlet
</Routes>
  • Related