CHF
CHF

Reputation: 294

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?

Upvotes: 0

Views: 1024

Answers (2)

Tan Nguyen
Tan Nguyen

Reputation: 1844

Qwik bind: attribute syntactic sugar is exactly for that:

import { component$, useSignal } from '@builder.io/qwik';

export interface IndexProps {
  count: number;
}

export default component$(() => {
    const count = useSignal('1');

    return (
      <div>
          <h1>Current number is: {count}</h1>
          <input type="number" bind:value={count}   />
      </div>
    );
});

For checkbox, you have bind:checked too

Upvotes: 2

Harsh Mangalam
Harsh Mangalam

Reputation: 1299


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>
});




Upvotes: 3

Related Questions