I have a filter where i sort data by date and answers, at first i was only filtering by date so i was using data.target.value and it was workin, since i have added the answers sorting i had to use the dataset, after doing this the data.target.dataset.dir & data.target.dataset.sort returns undefined
In a child component i have a select, SelectField renders the select with styled component :
<SelectField
onChange={props.triCallback}
>
<option data-sort="date" data-dir="desc">Filter by</option>
<option data-sort="date" data-dir="asc">Date asc</option>
<option data-sort="date" data-dir="desc">Date desc</option>
<option data-sort="answers" data-dir="asc">Answers asc</option>
<option data-sort="answers" data-dir="desc">Answers Desc</option>
</SelectField>
And in my App.js i have this method which handles the sorting :
constructor(props) {
super(props);
this.state = {
sorting : 'date',
sortDir : 'desc',
};
}
onTriChanged = data => {
const sorting = data.target.dataset.sort;
const sortDir = data.target.dataset.dir;
this.setState({
sortDir: sortDir,
sorting: sorting
}, () => {
this.fetchData()
});
};
CodePudding user response:
Since <SelectField>
actually renders a native <select>
underneath, then it is pretty straight-forward. The reason why data.target.dataset...
returns undefined is because those HTML5 data-
attributes that you want to retrieve actually reside on the selected <option>
element and not the <select>
element, the latter of which is referenced by data.target
.
Therefore, you will need to access the selection <option>
element, using the selectedIndex
property. The <select>
element allows us to access the nested collection of <option>
elements via the options
property.
onTriChanged = data => {
const selectedOption = data.target.options[data.target.selectedIndex];
const sorting = selectedOption.dataset.sort;
const sortDir = selectedOption.dataset.dir;
this.setState({
sortDir: sortDir,
sorting: sorting
}, () => {
this.fetchData()
});
};