1

I have the form with different inputs (an example is down) when I click someone from them and if another input is open I want to close them.

Maybe someone can say where is my an error? Thanks!

My code look:

class SignUp extends Component {
    constructor() {
      super();
      this.state = {
        selectedCode: false,
      };
    }
    componentDidMount() {
      document.addEventListener("click", this.handleClickOutside);
    }
    componentWillUnmount() {
      document.removeEventListener("click", this.handleClickOutside);
    }
    handleClickOutside(e) {
      if (e.target.id !== "code") {
        this.setState({
          selectedCode: false // here is an error
        });
      } else {
        console.log("YES CODE");
      }
    }
render (){
  return (
    <form >
      <input .../> 
      <input id="code" .../>
    </form>
}
Anon
  • 307
  • 1
  • 5
  • 17
  • Is it showing any error in browser console? – Vipin Yadav Aug 20 '19 at 13:57
  • You need to bind `this` to your event handler. On common way to do that is to use `bind` in your constructor: `this.handleClickOutside = this.handleClickOutside.bind(this);` See the linked question's answers for details. (Sometimes people use an arrow function, but having the method on the prototype works better with test frameworks.) – T.J. Crowder Aug 20 '19 at 13:58

1 Answers1

2

Try this

document.addEventListener("click", this.handleClickOutside.bind(this));
TKoL
  • 13,158
  • 3
  • 39
  • 73