简体   繁体   中英

Read (NOT SET) focus on an input in React?

Weird question that google hasn't helped with... how do I read if an input is focused in React?

What I'm wanting to do is hide the autocomplete div I've created if the input is not focused. Is there a way to do that?

As it is now, if you leave something in the text input and don't click on one of the autocomplete suggestions, the autocomplete div will stay there even after moving to search results and the detail page.

I already tried messing with how the div is displaying in the first place (it's rendering once the user starts typing which sets the options in a state array) by setting the array it pulls from to nothing on submit, but then it gives me the too many renders error.

Here's the form:

<form className="input-group mb-3" onSubmit={submit()}>
    <input
        type="text"
        className="form-control mr-sm-2"
        onChange={e => onSearch(e)}
        placeholder="Search to follow the money"
        value={searchedValue}
        />
    <Link to={`/searchresults/${selected}`} selected={selected}>
        <button
            type="submit"
            className="btn btn-light my-2 my-sm-0 shadow-sm"
            style={{
                height: "40px",
                borderRadius: "0px",
                MozBorderRadius: "0px",
                WebkitBorderRadius: "0px"
            }}
        >
        <img
                alt="search-icon"
                src={require("../../assets/its-a-bribe-search-punch-01.png")}
                style={{ width: "24px" }}
            />
        </button>
    </Link>
</form>

The autocomplete div is below the form like this:

<div className="container auto-complete-container">{renderSugs()}</div>

The onSubmit is currently just this:

const submit = () => {
        // setSuggestions([]);

    }

If I uncomment the setSuggestions it just gives me the too many renders error, even if the form hasn't been submitted yet?

This is my onSearch function:

    const onSearch = e => {
        setSearchedValue(e.target.value);
        const value = e.target.value;
        let suggestions = [];

        if (value.length) {
            suggestions = options.filter(option => {
                var name = option.name;
                // console.log("option", option)
                return name.toLowerCase().includes(searchedValue.toLowerCase());
            });
        }
        setSuggestions(suggestions);
    };

And to render the suggestions I have a function called renderSugs that maps through the suggestions and displays this for each:

<Link
    key={item.id + Math.random() * 100}
    to={`/politician/${item.id}`}
    style={{ textDecoration: "none", color: "black" }}
>
    <li
        onClick={() => {
             setSearchedValue(item.name);
             setSuggestions([]);
        }}
    >
        {item.name}
    </li>
</Link>

In the onClick there you'll see that I'm doing a setSuggestions, and it works here just fine. But when I try that same thing in the onSubmit it doesn't work???

Help?

Assuming it it a class based component (since you tagged the question state ) you can do it like this.

Wrap the suggestions div in a condition like this

{this.state.showSuggestions && <div className="container auto-complete-container">{renderSugs()}</div>}

And add an onFocus and onBlur to your input

<input
    type="text"
    className="form-control mr-sm-2"
    onChange={e => onSearch(e)}
    placeholder="Search to follow the money"
    value={searchedValue}
    onFocus={() => this.setState({showSuggestions: true})}
    
    />

<Link
    key={item.id + Math.random() * 100}
    to={`/politician/${item.id}`}
    style={{ textDecoration: "none", color: "black" }}
    >
    <li
        onClick={ async () => {
            await setSearchedValue(item.name);
            await setSuggestions([]);
            this.setState({showSuggestions: false})}
        }}
    >
        {item.name}
    </li>
</Link>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM