Reputation:
I have an app where I have listed a bunch of retailers for a car company. I use a state to determin which company is selected in the list, and they use the selected company to generate excellists and so forth, and up until recently I had all the retailers in one list and an onChange that set the state, however, the retailers have gotten so many that I implemented a searchfunction so that they dont have to scroll through 50+ retailers, but now I cant set state since, if they search for their own ID they will pop up in the selectbox, however I cant set state like this, is there any way to automatically set state to index 0 when I search?
Code here:
const FilterList = ({ ...props }) => {
return (
<div className="filter-list">
<div className="row">
<p className="headline text-left">Välj återförsäljare först</p>
</div>
<div className="row">
<div className="group">
<input
required
className="input-text"
type="text"
onChange={(ev) => props.updateFilter(ev)}
/>
<span className="highlight"></span>
<span className="bar"></span>
<label>Sök återförsäljare via id</label>
</div>
</div>
<AfSelect af={props.af} filterBy={props.filterBy} selectedAf={props.selectedAf} />
</div>
)
}
And here is the selectboxlist, which worked up until I implemented the searchfunction:
const AfSelect = ({ ...props }) => {
return (
<div>
<select className="select-input" onChange={(ev) => props.selectedAf(ev)}>
{
props.af.filter(item => item.afid.indexOf(props.filterBy) > -1)
.map((item, index) => {
return (
<option
key={index}
value={item.afid}
>
{item.name} {item.afid}
</option>
)
})
}
</select>
<p></p>
</div>
)
}
Thanks in advance!
Upvotes: 1
Views: 1152
Reputation: 59511
I would just modify the updateFilter()
function. Since you want this to apply whenever the user enter a filter, it makes sense to do this when the input value is changed:
updateFilter = (ev) => {
let obj = Object.assign({}, this.state);
if(ev.target.value.length > 0) {
let name = af.filter(item => item.afid.indexOf(ev.target.value) > -1)[0];
obj.selectedAf = name;
}
obj.filterBy = ev.target.value;
this.setState(obj);
}
The above is just a rough example of how you could implement this. The scope of certain variables, such as af
, etc is unknown based on the limited code you provided. But the logic should work.
But basically, if the input has something entered, do a filter
on af
and get the result at index 0
. This will be our selectedAf
. Then, save the state with the search term and the selected item.
Upvotes: 0