How do I access state from deeply nested components? #2206
-
Is there a way to access the value of say The obvious ways are to prop-drill the value or write my own Provider. What I'm looking for (if it's possible) is something like a |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
That's the way. You can also try constate if you're doing that very often: import { useRadioState, RadioGroup, Radio } from "ariakit";
import constate from "constate";
const [RadioProvider, useRadioContext] = constate(useRadioState);
function Wrapper() {
// can't useRadioContext here
return (
<RadioProvider defaultValue="orange">
<MyRadioGroup />
</RadioProvider>
);
}
function MyRadioGroup() {
const state = useRadioContext();
return (
<RadioGroup state={state}>
<RadioList />
</RadioGroup>
);
}
function RadioList() {
const state = useRadioContext();
console.log(state.value);
return (
<>
<Radio value="apple" />
<Radio value="orange" />
<Radio value="watermelon" />
</>
);
} |
Beta Was this translation helpful? Give feedback.
useRadioGroup
is just a custom hook that returns HTML props so you can create your ownRadioGroup
component. It doesn't give you access to the radio state.That's the way. You can also try constate if you're doing that very often: