SolidJSS
SolidJS13mo ago
12 replies
Leal

Unable to provide context to children

I'm writing a dropdown component, so I decided to use a context to provide tools to the children. I have defined the context as an object with some setters and accessors to a set of signals and no matter what I do, I can't get it from the children components.

I'm using SolidJS + SolidStart

Here's some code snippets:
type DropdownCtx = {
  rootElement: Accessor<HTMLDivElement>;
  setValue: Setter<any>;
  setSelected: Setter<HTMLElement | undefined>;
};

const DropdownContext = createContext<DropdownCtx>();

export const DropdownComponent = <T extends any>(props: DropdownProps<T>) => {
  let rootElement!: HTMLDivElement;
  const rootElementAccessor = () => rootElement;

  const children = solidChildren(() => props.children); // I import solid's children fn as solidChildren

  const [value, setValue] = createSignal(props.value);
  const [selected, setSelected] = createSignal<HTMLElement | undefined>(undefined);

  // ...

  const context: DropdownCtx = {
    rootElement: rootElementAccessor,
    setValue,
    setSelected,
  };

  // ...

  return (
    // ...
    <dialog
      class='dropdown__popup'
      id={idPopup()}
      open={isOpen()}
    >
      <DropdownContext.Provider value={context}>
        {children()}
      </DropdownContext.Provider>
    </dialog>
  );
};


export const DropdownItemComponent = <T extends any>(props: DropdownItemProps<T>) => {
  // ...

  const context = useContext(DropdownContext);

  if (!context) {
    throw new Error("Missing context");
  }

  // ...
};

// Usage

<DropdownComponent>
  <DropdownItemComponent>
    <span>help :(</span>
  </DropdownItemComponent>
</DropdownComponent>


I have tried:

- Using props.children instead of children()
- Moving the context provider up
- Declaring the context as a store using createStore

I can't get Solid to provide the context and I don't really know the reason, every try throws the error :(
Was this page helpful?