javascriptdata-bindingqwik

Bidirectional props in qwik


Is is possible to create a bidirectional property for a component in qwik?

I want to create a custom input component for a size displaying amount and unit. To avoid unnecessary events i simply want to bind the value bidirectional to use it like this:

Size: <SizeInput value={model.size} />

Therefore i would create a component like this:

import { component$ } from '@builder.io/qwik';
export const SizeInput = component$((props: { value: number }) => {
  props.value = 123; //Simulate manipulating the value in on-blur of one of both sub elements.
  return (
    <>
      <input type="number" value={props.value}/>
      <select>
        <option>Unit 1</option>
        <option>Unit 2</option>
      </select>
    </>
  );
});

When I execute this code the debugger tells me that...

props are immutable

What is the correct way of doing this? Do I really need to provide a complete store or a function as QRL?


Solution

  • 
    import { component$, useSignal, $, type PropFunction } from '@builder.io/qwik';
    
    interface SizeInputProps {
      value: number;
      onInput$: PropFunction<(e: Event) => number>
    }
    export const SizeInput = component$((props: SizeInputProps) => {
      const { onInput$, value } = props
      return (
        <>
          <input onInput$={onInput$} type="number" value={value} />
          <select>
            <option>Unit 1</option>
            <option>Unit 2</option>
          </select>
        </>
      );
    });
    
    
    export default component$(() => {
      const input = useSignal(123)
      const handleChange$ = $((e: Event) => input.value = ((e.target as HTMLInputElement).valueAsNumber))
      return <div>
        <div>{input.value}</div>
        <SizeInput value={input.value} onInput$={handleChange$} />
      </div>
    });