'React - event.target is undefined when trying to filter React-select options
I'm pretty new to React and JavaScript, I'm trying to grab the value of a react-select dropdown option to use in a filter. The code below throws "Uncaught TypeError: event.target is undefined".
const [filter, setFilters] = useState({})
const handleFilters = (event)=> {
const value = event.target.value;
setFilters({
[event.target.name]: value,
});
};
console.log(filter);
React-Select
<Select name="category" onChange={ handleFilters } options={filterOptions} className='dropdown'/>
React-Select Options
const filterOptions = [
{ value: 'value1', label: 'label1' },
{ value: 'value2', label: 'label2' },
{ value: 'value3', label: 'label3' },
{ value: 'value4', label: 'label4' }
];
the consolelog I'm expecting when choosing the first dropdown option would be - { category, value1 }
Solution 1:[1]
Please be advised that react-select's onChange doesn't get called with the native select's onChange event but with the following API:
const onChange = (option: Option | null, actionMeta: ActionMeta<Option>) => {
...
}
So your handler function should look like this
const handleFilters = (option) => {
setFilters({
[event.target.name]: option,
});
};
Solution 2:[2]
You can make the below change in the onChange event
<Select name="category" onChange={(e)=> handleFilters(e) } options={filterOptions} className='dropdown'/>
Solution 3:[3]
This is happening because the onChange handler of react-select directly returns the option(Object) that is selected.
So, for example event will contain {label:"label1",value:"value1"}
You can have a look at this codesandbox for reference
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Mundruku |
| Solution 3 | Omkar |
