Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React input focus event to display other component

I was read some tutorial about this. They told me should using ref to do that. But It's very general.

Here is my problem: Basically in Header component include NavBar, SearchBar and ResultSearch component.

const Header = () => {
return (
    <header className="ss_header">
        <Navbar />
        <SearchBar />
        <ResultSearch />
    </header>
);
};

And In SearchBar component. Whenever I focused on input text. It emit an event and display ResultSearch component by any way (changing style, or ...).

class SearchBar extends Component{
render() {

    return (
        <div className="search_bar">
            <section className="search">
                <div className="sub_media container">
                    <form method="GET" action="" id="search_form">
                        <Icon icon="search" />
                        <span className="autocomplete">

                        <input
                            className="search_input"
                            autoCorrect="off"
                            autoComplete="off"
                            name="query"
                            type="text"
                            placeholder="Search for a movie, tv show, person..." />
                    </span>
                    </form>
                </div>
            </section>
        </div>
    );
}
}

Style in ResultSearch component. I was set display: none.

.results_search { display: none; }

I think ResultSearch will receive an event from SearchBar and set back display: block for ResultSearch component. Is possible?

How can I handle that? My Code here: https://codesandbox.io/s/3xv8xnx3z5

like image 888
Thuan Nguyen Avatar asked Jan 28 '23 21:01

Thuan Nguyen


2 Answers

Still not sure what you're trying to achieve.

This is the way you can handle visibility of result of the search. Let me know if this isn't what you're looking for.

https://codesandbox.io/s/7jvz31xr66

like image 31
Amin Paks Avatar answered Jan 30 '23 10:01

Amin Paks


only you should convert Header component like following:

class Header extends Component {
  state = {
    focus: false
  };

  handleInputFocus = () => {
    this.setState({ focus: true });
  };

  handleInputBlur = () => {
    this.setState({ focus: false });
  };

  render() {
    return (
      <header className="ss_header">
        <SearchBar
          onFocus={this.handleInputFocus}
          onBlur={this.handleInputBlur}
        />
        {this.state.focus ? <ResultSearch /> : null}
      </header>
    );
  }
}

and also in SearchBar component add following attributes to your input:

onFocus={this.props.onFocus}
onBlur={this.props.onBlur}

also, you should remove your CSS about result box.

And, you can see the updated code on the following sandbox:

https://codesandbox.io/s/mmj46xkpo9

like image 136
Omid Nikrah Avatar answered Jan 30 '23 12:01

Omid Nikrah