Home > OS >  Cannot read properties of undefined (reading 'target)
Cannot read properties of undefined (reading 'target)

Time:05-05

first post here. I tried searching around the forum but none of the answers seems to work in my case. I'm pretty new to React, and have an issue with my onChange handler.

In my parent component I have the following:

    // User registration - Onchange handler

    const handleChange = (value, event) => {
      // console.log(event.target.value);
      setFormValue({
        ...formValue,
        [event.target.name]: value,
      });
    };

And basically the parent component renders a multi step registration form, which renders the different components based on a state, here is the conditional for the username:

 {step === 1 ? <Username handleChange={handleChange} formValue={formValue} /> : null}

In the child I have the following input component:

export const Username = ({formValue, handleChange}) => {
  const username = formValue; 
  
    return (
      <View>
      <Input 
      placeholder="Username..."
      onChangeText={handleChange}
      value={formValue.username}
      name={username} />
      </View>
    )
  }

And the input component:

const Input = (props, name) => {

  return (
    <Animated.View style={[styles.inputSection, inputAnimated]}>
        <TextInput style={styles.input} placeholder={props.placeholder} placeholderTextColor={theme.colors.lightP} fontSize={16} {...props}/>
    </Animated.View>
  )
}

I'm not sure why I get the error:

Cannot read properties of undefined (reading 'target)

Would appreciate any help. Console.log of event.target returns undefined.

CodePudding user response:

This happens because onChangeText passes the input's value automatically to the function that's assigned to it, not passing the event itself

If you want to use the event => use onChange instead of onChangeText

CodePudding user response:

Here in the documentation you can read for the onChange event

You are using onChangeText

So onChangeText has just text value, but if you want to have the native event you have to use onChange.

Then access it in you method

    const handleChange = ({ nativeEvent: { eventCount, target, text} }) => {
      // console.log(event.target.value);
      setFormValue({
        ...formValue,
        [target]: text,
      });
    };
  • Related