Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

reactjs - Using onSelect property of materialUI autocomplete form

I'm trying to create a search form with autocomplete suggestions that pulls data from API. I got everything to work in terms of displaying data and selection, but I would like to automatically take the user to the related page once they select one of the suggestions.

<Autocomplete
                id="search-input"
                freeSolo
                disableClearable
                options={playerList}
                getOptionLabel={(option) => option.nickname}
                style={{ width: 200}}
                **onClick={console.log("you clicked")}
                onSelect={(val)=> window.location.href = "/player-statistics/"+val.nickname+"-"+val.account_id+"-"+server}**
                onInputChange={(event, newInputValue) => {
                    setInputValue(newInputValue);
                    if (newInputValue.length >= 3) {fetchPlayers(newInputValue)}
                }}
                renderInput={(params) => <TextField {...params} label="Search Players" variant="outlined" margin="normal" />}
            />

I have tried with onChange and onSelect, but they are both reloading the page continuously whenever you press the search field or start typing.

The idea is to skip the need to click "search" button.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you select a suggested name, onInputChange is triggered.
There you need to put the logic for changing the location.
Then the user does not have to click anything else.
If you do not want the page to change when the user only types a single character,
then you need to write logic for that inside onInputChange.

sth. like

   // inside onInputChange
   if(isASuggestedName(newInputValue)) {
       //...change location
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...