I'm new in ReactJs. In my application, I have inserted the following code to validate textArea, but when I type on it, it throws following error.
NewBrand.js:67 Uncaught TypeError: Cannot read property 'validateName' of undefined
at handleNameChange (NewBrand.js:67)
at TextArea._this.handleTextareaChange (TextArea.js:94)
at HTMLUnknownElement.callCallback (react-dom.development.js:100)
at Object.invokeGuardedCallbackDev (react-dom.development.js:138)
at Object.invokeGuardedCallback (react-dom.development.js:187)
at Object.invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:201)
at executeDispatch (react-dom.development.js:461)
at executeDispatchesInOrder (react-dom.development.js:483)
at executeDispatchesAndRelease (react-dom.development.js:581)
at executeDispatchesAndReleaseTopLevel (react-dom.development.js:592)
My code looks like follows:
handleNameChange(event) {
const value = event.target.value;
this.setState({
name: {
text: value,
...this.validateName(value)
}
});
}
isFormInvalid() {
if(this.state.name.validateStatus !== 'success') {
return true;
}
}
validateName = (nameText) => {
if(nameText.length === 0) {
return {
validateStatus: 'error',
errorMsg: 'Please enter the Brand name!'
}
} else if (nameText.length > POLL_QUESTION_MAX_LENGTH) {
return {
validateStatus: 'error',
errorMsg: `Name is too long (Maximum ${POLL_QUESTION_MAX_LENGTH} characters allowed)`
}
} else {
return {
validateStatus: 'success',
errorMsg: null
}
}
}
Please hepl me to resolve this issue
When you're hooking up the change handler (probably in your render method) your jsx looks something like this
<textarea onChange={ this.handleNameChange } ...
Change it to
constructor(props){
super(props);
this.handleNameChange = this.handleNameChange.bind(this);
}
<textarea onChange={this.handleNameChange} ...
This ensures that this
still refers to the Component object when the change callback runs.
Please note you are not recommended to bind the function directly in render or anywhere else in the component except constructor. Because binding in render causes a new function to be created in bundle file every time the component renders so we are not recommended to do that.
Like wise wherever you have event handler functions bind them in constructor and use the reference like mentioned above