SolidJSS
SolidJSโ€ข2y agoโ€ข
9 replies
Liquido

How to pass props to context reactively?

I have a context that accepts props and then provides the prop values to its consumer components:

type FormGroupProps = { hasError?: boolean, name: string, children: JSXElement };

type FormGroupContextValue = { hasError: boolean, name: string };
const FormGroupContext = createContext<FormGroupContextValue>({
  hasError: false, name: ''
});

export function FormGroup(props: FormGroupProps) {
  return (
    <FormGroupContext.Provider
      value={{ hasError: Boolean(props.hasError), name: props.name }}
    >
      {props.children}
    </FormGroupContext.Provider>
  );
}

export function useFormGroup() {
  return useContext(FormGroupContext);
}

export function TestComponent() {
  const group = useFormGroup();
  return (
    <pre>
      Has error: {group.hasError}
      Name: {group.name}
    </pre>
  )
}

// Usage
const [errorA, setErrorA] = createSignal(false);

return <>
  <FormGroup name="a" hasError={errorA()}>
    <TestComponent />
  </FormGroup>
  <button onClick={() => setErrorA(err => !err)}>Toggle error</button>
</>


Playground link: https://playground.solidjs.com/anonymous/d7a38bbe-fa34-49c9-9d8f-7211839257ad

How do I make the props passing to the context value reactive?
Quickly discover what the solid compiler will generate from your JSX template
Was this page helpful?