Skip to content
Advertisement

antd wrapping custom input with auto-complete cause: Cannot read property ‘value’ of undefined

In antd with react, If I’ve something like the below, everything works fine:

<Form>
  <Form.Input>
    <SomeIntermadiateComp/>
...   

And that some intermediate component looks like this:

const SomeIntermadiateComp = React.forwardRef(({ value, onChange }: Props, ref: any) => (
  <Input
    ref={ref}
    value={value}
    onChange={(event) => {
      console.log(event);
      if (onChange) onChange(event.target.value);
    }}
  ...

Everything works fine, until, I try to add AutoComplete

When I wrap the intermediate component with AutoComplete, like:

<Form>
  <Form.Input>
    <AutoComplete>
        <SomeIntermadiateComp/>
        ...   

Then on changing or giving input to intermediate component cause error. Saying:

Uncaught TypeError: Cannot read property 'value' of undefined
    at onInputChange (index.js:104)
    at onChange (SingleSelector.js:71)
    at onChange (Input.js:77)
    at onChange (SomeIntermadiateComp.tsx:28)

Complete trace is something like:

onInputChange
node_modules/rc-select/es/Selector/index.js:104
  103 | var onInputChange = function onInputChange(event) {
> 104 |   var value = event.target.value; // Pasted text should replace back to origin content

onChange
node_modules/rc-select/es/Selector/SingleSelector.js:71
 69 | onChange: function onChange(e) {
  70 |   setInputChanged(true);
> 71 |   onInputChange(e);

onChange
node_modules/rc-select/es/Selector/Input.js:77
  76 | onChange: function onChange(event) {
> 77 |   _onChange(event);

onChange
src/components/SomeIntermadiateComp.tsx:28
  26 |     onChange={(event) => {
  27 |       console.log(`${event.target.value}--`);
> 28 |       if (onChange) onChange(event.target.value);

And the funny part is, console.log(`${event.target.value}--/`); logs the key pressed.

Advertisement

Answer

Solution:

if (onChange) onChange(event);

I guess you should NOT write if (onChange) onChange(event.target.value); because inner onChange function needs event argument, not value.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement