Reputation: 13
I am creating a form element within my React app. When I try to save the form value in a const, I get an error "Uncaught TypeError: Cannot read property 'value' of undefined". Here is a snippet of my component:
export default class LookupTag extends React.Component {
state= {
error: undefined
};
getProductData = (e) => {
e.preventDefault();
const upc = e.target.elements.option.value;
const error = this.props.getProductData(upc);
this.setState(() => ({ error }));
};
render(){
return(
<div>
{this.state.error && <p>{this.state.error}</p>}
<form onSubmit={this.getProductData}>
<input type='text' name='upc'/>
</form>
</div>
)
}
}
Please note that I am using a babel plugin called "transform-class-properties" which allows me to remove the constructor entirely (aka it is not a binding problem). The specific error is referencing the line where I set "const upc = e.target.elements.option.value;". I have also tried just using "e.target.value" but the same error occurs. Any ideas would be appreciated! Please let me know if you need any more info :)
Upvotes: 1
Views: 1511
Reputation: 112777
You don't have an element option
, so e.target.elements.option
will give you undefined
, and trying to access value
on that will give rise to your error.
e.target.elements.upc.value
will work.
getProductData = (e) => {
e.preventDefault();
const upc = e.target.elements.upc.value;
const error = this.props.getProductData(upc);
this.setState(() => ({ error }));
};
Upvotes: 1