How to dynamically inject context provider into a child component? #1657
Closed
GakkiiSmile
started this conversation in
General
Replies: 2 comments 1 reply
-
There's no way to do this if you're using it on resolved children. You'll need to change the structure for this to work, I would say something like a render prop is better. |
Beta Was this translation helpful? Give feedback.
0 replies
-
I recently had similar question on this, and got a workaround. import {JSX, children as Children, For} from 'solid-js';
const App = ()=>{
<div>
<Compact>
<Child />
<Child />
</Compact>
<NotCompact>
<Child isFirstItem />
<Child />
<Child isLastItem />
</NotCompact>
</div>
}
const Compact = ({children})=>{
const c = Children(()=>children).toArray();
const someValue="some value";
// technically context is not even needed, but added it in this sample to demonstrate context is also working.
return (
<For each={c}>
{(childProps,idx)=><MyContext.Provider idx={idx} ><ChildToRender idx={idx} {...childProps} isCompact={true} /></MyContext.Provider>}
</For>
)
}
const NotCompact = ({children})=>{
const c = Children(()=>children).toArray();
const someValue="some value";
return (
<For each={c}>
{(childProps,idx)=><MyContext.Provider idx={idx}><ChildToRender idx={idx} {...childProps} isCompact={false} /> </MyContext.Provider>}
</For>
)
}
const Child = (props)=>{
return props; // as unknown as JSX.Element (in typescript)
}
const ChildToRender = ({isCompact=false, isFirstItem=false, isLastItem=false})=>{
const idx = useContext(MyContext);
return (<p>
<span style={{ "margin-right": "10px" }}>
isFirstItem: {data?.isFirstItem?.toString()}
</span>
<span>idx from context: {idx}</span>
<span>isLastItem: {data?.isLastItem?.toString()}</span>
</p>)
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
https://playground.solidjs.com/anonymous/81ebd841-1499-4ad8-bfec-24cde0290c83
Beta Was this translation helpful? Give feedback.
All reactions