Reputation: 834
I am a beginner in React and trying to understand binding and events. I have created a learning project and want to validate the dropdown on onChange. If no value is selected from the drop-down, then display an error message.
Note: I'm using a custom library which has attributes for inValid and error with SelectField component. If inValid is set to true, it will trigger an error message.
I've tried finding solutions on multiple sources and trying to resolve this since hours. Please have a look. Thanks in advance.
WeatherOptionsView.js
class WeatherOptionsView extends React.Component {
constructor(props) {
super(props);
this.state = { reasonState: false, selectValue: null };
}
validateState(event) {
if(!! event.target.selectValue ) {
this.setState({reasonState: true});
}
}
render() {
const cx = classNames.bind(styles);
return (
<ContentContainer fill>
<Spacer marginTop="none" marginBottom="large+1" marginLeft="none" marginRight="none" paddingTop="large+2" paddingBottom="none" paddingLeft="large+2" paddingRight="large+2">
<Fieldset legend="City">
<Grid>
<Grid.Row>
<Grid.Column tiny={3}>
<SelectField selectId="city" required placeholder="Select" label={["City:"]} error={["Error message"]} onChange={this.validateState.bind(this)} isInvalid={this.state.reasonState} value={this.state.selectValue}>
<Select.Option value="City1" display="City1" />
<Select.Option value="City2" display="City2" />
</SelectField>
</Grid.Column>
</Grid.Row>
</Grid>
)}
/>
</ContentContainer>
);
}
}
export default injectIntl(WeatherOptionsView);
Uncaught TypeError: Cannot read property 'selectValue' of undefined
Upvotes: 0
Views: 97
Reputation: 61
As it says Uncaught TypeError: Cannot read property 'selectValue' of undefined
, event.target value is undefined. Also you have to set selectValue
in the local state onChange to send value prop for .
Upvotes: 1
Reputation: 349
Your problem is not in the binding but in your validateState
implementation. You are expecting event
, but the SelectField component is probably passing value. The value doesn't have the target attribute that you want. Try something like this, instead:
handleChange(value) {
this.setState({selectValue: value, reasonState: !value});
}
// and then in the render:
<SelectField onChange={this.handleChange.bind(this)}>
{/* ... */}
</SelectField>
Upvotes: 2