Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing Multiple State Variables through Outlet Context

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading