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
McBrincie212OP4mo ago
(oops accidentally added suggestions) the reason as to why is so i can call a function that is hosted in DrawToolsMenu from PixelArtCanvas
REEEEE
REEEEE4mo ago
McBrincie212
McBrincie212OP4mo ago
ok im a bit confused on contexts how do i use them exactly, what do they serve?
REEEEE
REEEEE4mo 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
McBrincie212OP4mo ago
tbh i don't really get em im trying to watch a tutorial to learn
Grahf
Grahf4mo 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
McBrincie212OP4mo ago
is it a good practice if i may expose a export function in the tsx?
Grahf
Grahf4mo 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
Madaxen864mo 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
McBrincie212OP4mo ago
i don't like adding unnecessary bloat to my application
Want results from more Discord servers?
Add your server