SoftWorker
SoftWorker

Reputation: 95

Passing props from outlet to parent using React Router 6

I'm using React Router V6 and im trying to figure out if I can pass props from nested routes which are rendered using Outlet components. I can't seem to figure it out though. Can anyone help?

E.g. trying to pass the title prop from BleTable ("Bluetooth") to App

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App title="**Title from outlet**" />} >
          <Route path="ble" element={<BleTable title="Bluetooth"/>}/>
          <Route path="create-user" element={<UserForm/>}/>
        </Route>
      </Routes>

    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

Upvotes: 7

Views: 6097

Answers (1)

Drew Reese
Drew Reese

Reputation: 202605

You can't pass props, per se, but you can provide a context value to the Outlet that App is rendering that the routed components can access via the useOutletContext hook.

Example:

const AppLayout = () => {
  const [title, setTitle] = useState("");

  return (
    <>
      <h1>App: {title}</h1>
      <Outlet context={{ setTitle }} /> // <-- provide context value
    </>
  )
};

const BleTable = ({ title }) => {
  const { setTitle } = useOutletContext(); // <-- access context value

  return (
    <>
      <h1>BleTable</h1>
      <button type="button" onClick={() => setTitle(title)}>Update App Title</button>
    </>
  );
}

...

<BrowserRouter>
  <Routes>
    <Route path="/" element={<AppLayout />}>
      <Route path="ble" element={<BleTable title="Bluetooth" />} />
      <Route path="create-user" element={<UserForm/>}/>
    </Route>
  </Routes>
</BrowserRouter>

Edit passing-props-from-outlet-to-parent-using-react-router-6

Upvotes: 11

Related Questions