How To Communicate Between Components

suppose this setup i got here
<div>
<DrawToolsMenu />
<PixelArtCanvas />
</div>
<div>
<DrawToolsMenu />
<PixelArtCanvas />
</div>
I want to PixelArtCanvas have a reference to DrawToolsMenu. How can i achieve that?
10 Replies
McBrincie212
McBrincie2123w ago
(oops accidentally added suggestions) the reason as to why is so i can call a function that is hosted in DrawToolsMenu from PixelArtCanvas
McBrincie212
McBrincie2123w ago
ok im a bit confused on contexts how do i use them exactly, what do they serve?
REEEEE
REEEEE3w ago
You define a Provider that wraps the children that you want to have access to shared functions. In this case, you can define a Provider around DrawToolsMenu and PixelArtCanvas and place functions you want both to have access to in there. You can then access them with
const myContext = useContext(WhateverTheContextIs)

myContext.function()
const myContext = useContext(WhateverTheContextIs)

myContext.function()
McBrincie212
McBrincie2123w ago
tbh i don't really get em im trying to watch a tutorial to learn
Grahf
Grahf3w ago
They are generally used for global state. Like if you wanted a signal to be able to be read and set by any component in your app you'd use a context provider. You can limit them to just a group of components instead of all components too
McBrincie212
McBrincie2123w ago
is it a good practice if i may expose a export function in the tsx?
Grahf
Grahf3w ago
That's what I like to do......if you're doing what I think you're doing. Export a function to set and get a signal in the provider
Madaxen86
Madaxen863w ago
You can have a look at kobalte.dev's Dialog component. There's a Root which provides a context for all the components inside it https://github.com/kobaltedev/kobalte/blob/main/packages/core/src/dialog/dialog-root.tsx
GitHub
kobalte/packages/core/src/dialog/dialog-root.tsx at main · kobalted...
A UI toolkit for building accessible web apps and design systems with SolidJS. - kobaltedev/kobalte
McBrincie212
McBrincie2123w ago
i don't like adding unnecessary bloat to my application
Want results from more Discord servers?
Add your server