Forward reference a Component's state in Template
I try to wrap a Trigger and a Display component in a state managing component like so
Is this possible? Background is, I want the triggering component to be dynamic. Might be a button, checkbox, input field, etc. And I would like to avoid having to hardcode every event handler
Maybe there's also a more straightforward way to achieve this instead of this approach?
Cheers!
9 Replies
Concrete use-case which might make the issue easier to understand:
I have a Modal component and want to combine it with a dynamic Trigger component.
Wrapper is supposed to create the modal's open state and share it between the trigger and the modal itself - but Button should be replaceable with any other component. For this reason, I want to be able to hook into the Wrapper's setter from the template context. Probably not possible like this but there must be some way to achieve something similar?!
you can use context https://www.solidjs.com/docs/latest/api#createcontext
SolidJS
Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.
Thanks for the suggestion, but it's not really what I'm looking for afaik.
With a context the core of the question remains the same. I'd have to hard-code the handler of the trigger in a sub-component because I cannot access the created Context from the parent's JSX template. Unless I'm missing something
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
Okay but if I want to replace
Button
with a Form
, or Checkbox
or whatever, I'd have to create an extra component for each of those cases. My goal is to not have to do that and dynamically bind the openModal
state with whatever my component uses as a handler, e.g.
It's possible that it's just not do-able. But I was wondering if there is a way to make it happennot sure what you mean
like so it accepts it as a prop?
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
Not really. Just to be able to reference the created context from the outside scope before it's created. I don't know how else to describe it 😄
I know I could create a component for each of those cases individually, like
But then I have to create
FormModal
, ButtonModal
, CheckboxModal
, ...
Which I wouldn't have to do if I could reference the state from the template itself, like I said above:
Your last example looks it can be used in the way I mean
Thank you for your help. However, I can't get it to work. I don't think it's designed to work like that. Or I'm doing something wrong.
With this jsx
Context works fine in Modal, but is undefined in the triggerModal callback :/
you shouldn't be wrapping
triggerModal()
in a thunk, i.e.
also, the context will be undefined if you try to read it inside the event handler since that is called outside the context