Ndx
Ndx

Reputation: 647

hiding a form input on click outside of its onlclick div

I have a form composed of a one input, and I want to toggle it. The form displays when you click on div, and I want to hide the form when i click outside of div. How do I do that in React?

class InputToggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showInputForm: false
    };
  }
  onClickAction(e) {
    e.preventDefault();
    this.setState({ showInputForm: true });
  }
  render() {
    if (this.state.showInputForm) {
      return (<input type="text" />)
    }
    return (
      <div onClick={this.onClickAction.bind(this)}>
        <h1>value</h1>
      </div>
    );
  }
}

How to set the state showInputForm to false on a click outside of div?

Upvotes: 0

Views: 894

Answers (1)

Dane
Dane

Reputation: 9572

You have to use the onBlur event listener on the input element. See code:

class InputToggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showInputForm: false
    };
  }
  onClickAction(e) {
    e.preventDefault();
    this.setState({ showInputForm: true });
  }
  componentDidUpdate() {
    if (this.state.showInputForm) {
      this.input.focus();
    }
  }
  render() {
    if (this.state.showInputForm) {
      return (
        <input
          ref={(el) => this.input = el}
          onBlur={() => this.setState({ showInputForm: false })}
          type="text" />
      );
    }
    return (
      <div onClick={this.onClickAction.bind(this)}>
        <h1>value</h1>
      </div>
    );
  }
}

Note that I had to focus the input when it is rendered. The onBlur event won't be fired if the input is not in focus.

See working pen.

Upvotes: 1

Related Questions