Home > Back-end >  Getting 'Uncaught TypeError: handleChange is not a function' while trying to read input fr
Getting 'Uncaught TypeError: handleChange is not a function' while trying to read input fr

Time:04-02

I am trying to call this handleTextChange function (in Form.js) from another component in a different file (Input.js), but it throws the error:

Uncaught TypeError: handleChange is not a function

I am new to learning ReactJS, and I'm following a tutorial, so do not know much about the language yet. This method was working for the course instructor, so I am not sure where I am going wrong with this.

Here is my function. I am calling it from inside the render method of my Class component Form

handleTextChange = name => event => {
        this.setState({ [name]: event.target.value });
        console.log('name', name)
    }

<Input 
   name='userName' 
   label='Username' 
    defaultValue={userName} 
    handleChange={this.handleTextChange} 
/>
const Input = ({ name, label, value, handleChange }) => (
    <Component>
        <Label htmlFor={name}>{label}</Label>
        <StylizedInput onChange={handleChange(name)} type='text' defaultValue={value}/>
    </Component>
)

CodePudding user response:

you have to call handleChange in Your component like this if you want to pass some arguments

<StylizedInput onChange={() => handleChange(name)} type='text' defaultValue={value}/>

without function arguments you can call the function like this

 <StylizedInput onChange={handleChange} type='text' defaultValue={value}/>

CodePudding user response:

this.handleTextChange will be returning undefined because you're missing a bind. Your class component should look like this:

handleTextChange = name => event => {
        this.setState({ [name]: event.target.value });
        console.log('name', name)
    }

this.handleTextChange = this.handleTextChange.bind(this);

<Input 
   name='userName' 
   label='Username' 
    defaultValue={userName} 
    handleChange={this.handleTextChange} 
/>
  • Related