Passing Multiple State Variables through Outlet Context

Viewed 310

I'm trying to utilize react-router's useOutletContext to pass a few state variables from my top down component (Page) to children generated in the outlet

I'm getting a bit stuck on how to add multiple state variables into context.

Working Code for a Single State Variable

Parent Component

<Outlet context={[currentValue1, setCurrentValue1]} />

Child Component

const [currentValue1, setCurrentValue1] = useOutletContext();

return (<h1>{currentValue1}</h1>)

How would I pass through [currentValueN, setCurrentValueN] in addition to currentValue1?

1 Answers

You can pass more than two elements in an array.

<Outlet
  context={[
    currentValue1, setCurrentValue1,
    currentValue2, setCurrentValue2,
    ...
    currentValueN, setCurrentValueN
  ]}
/>

You could also use an object. This avoids the need to skip destructuring via the array when you want the Nth element, i.e. const [,,,,,,currentValueN] = useOutletContext();

<Outlet
  context={{
    currentValue1, setCurrentValue1,
    currentValue2, setCurrentValue2,
    ...
    currentValueN, setCurrentValueN
  }}
/>

...

const { currentValueN } = useOutletContext();

It's really up to you how you want to pass all the data/properties.

Related