I have been working on react-select component which renders dropdown menu(Image mentioned below). It selects the value from the dropdown by default even though I have not selected it.
Here is the Dropdown menu picture it renders and it selects 60 minutes value
import React from 'react';
import { uniqueId } from 'lodash';
import Select from 'react-select';
import LabelWrapper from '../LabelWrapper';
import AlertWrapper from '../AlertWrapper';
const styles = require('./styles.module.scss');
type Props = {
multi: boolean;
options: Array<{ label: string; value: string }>;
onChange: (selectElementValue: { label: string; value: string }) => {};
onBlur: () => {};
value: { value: string, label: string};
error: string;
placeholder: string;
label: string;
horizontalLabel: boolean;
required?: boolean;
};
class CreatableSelect extends React.Component<Props, {}> {
inputId: string;
constructor(props) {
super(props);
this.inputId = uniqueId('id_');
}
render() {
const disabled = this.props.options.length === 0;
return (
<LabelWrapper
forId={this.inputId}
error={!!this.props.error}
label={this.props.label}
horizontal={this.props.horizontalLabel}
required={this.props.required}
>
<AlertWrapper>
<Select.Creatable
multi={this.props.multi}
options={this.props.options}
onChange={e => this.props.onChange(e.value)}
disabled={disabled}
placeholder={this.props.placeholder}
className={this.props.error ? styles.hasError : null}
onBlur={this.props.onBlur}
value={this.props.value}
inputProps={{ id: this.inputId }}
/>
</AlertWrapper>
{this.props.error && (
<span className="help-block">{this.props.error}</span>
)}
</LabelWrapper>
);
}
}
export { CreatableSelect };
However, I want to clear the value from the dropdown but, it gives me error in console:
Uncaught TypeError: Cannot read properties of null (reading 'value')
what is possibly going wrong in my code?
CodePudding user response:
From the react-select
docs, here is the onChange
event's first parameter, newValue
newValue: IsMulti extends true ? ReadonlyArray<Option> : SingleValue One of<null, Option>
So, it's possible for newValue
to be null
. You'll have to do a null
check or use any other syntax that enables you to do so.
The API might not be intuitive to somebody used to using onChange
on a select
directly, but they've chosen it and you'll have to abide by it if you want to use it.
Some examples of what you could do:
e && e.value
e?.value
e && this.props.onChange(e.value)
And probably you want to change the parameter name on your event handler to newValue
or something else.