react-datalist-input icon indicating copy to clipboard operation
react-datalist-input copied to clipboard

Propagate value of selected item as onChange event on input

Open mazeForGit opened this issue 2 years ago • 3 comments
trafficstars

Problem I can get changes on input via onChange event and changes on item-selection via onSelect. But on item-selection the input.value is changed as well. Event onChange is therefore a combination of input.value change from user input as well as item selection.

Solution onSelect should trigger onChange with new value as well

used environment "bootstrap": "^5.3.1", "react-bootstrap": "^2.8.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-datalist-input": "^3.2.1"

mazeForGit avatar Nov 17 '23 08:11 mazeForGit

Hey @mazeForGit, thanks for opening the issues. Yes, onChange should fire whenever the input field changes, including on selection. Let me have a look later today and maybe add a fix! :)

andrelandgraf avatar Nov 17 '23 18:11 andrelandgraf

Hey! Just looked into this and I think you probably want to use the value and setValue states instead of onChange:

export default function Index() {
  const [inputValue, setInputValue] = useState('');
  const { value, setValue } = useComboboxControls();

  // onChange is only updated on input change by the user
  console.log('onChange value', inputValue);
  // `value`/`setValue` will update `value` both on input change and on select
  console.log('setValue value', value);

  return (
    <DatalistInput
    label="Select your favorite flavor"
    placeholder="Chocolate"
    items={items}
    value={value}
    // setValue receives the latest string value of the input field
    setValue={setValue}
    onSelect={(i) => console.log("onSelect", i)}
    inputProps={{
      // onChange called on input change, receives the change `Event`
      onChange: (e) => setInputValue(e.target.value),
    }}
  />);
}

andrelandgraf avatar Nov 17 '23 22:11 andrelandgraf

I agree that this is confusing. The inputProps are passed down to the underlying input element, and the onChange on input is not triggered when programmatically updating the input value. That's why setValue exists; it is called both onChange and onSelect to update the input value accordingly.

So no bug, just a bit confusing. In the next iteration of this package, I may want to remove value and setValue in favor for value and onChange input props to trigger/update on select, as it does when using the native HTML input & datalist elements.

andrelandgraf avatar Nov 17 '23 22:11 andrelandgraf