Search code examples
javascriptreactjsreact-reduxshow-hide

Reactjs onFocus/onBlur hide/show element


I have a two input field what I want is if I click the first one/ if I input the first one the 2nd field must be hidden. I have the codes here but I think I have some error in the syntax. sorry, i'm new in this language.

constructor(props) {
    super(props);
    this.state = {data: ''}; 
}

onClick() {
    this.setState({ data : 'hidden'});
}

const elements = (
 <div>
     <label>Pick-up</label>
     <PlacesAutocomplete 
        inputProps={inputProps} 
        ref="pickupVehicle" 
        value={this.state.pickup} 
        onChange={this.handlepickupVehicle} 
        onClick={this.onClick} />
 </div>
 <div {this.state.data}>
     <label>Drop-off</label>   
     <PlacesAutocomplete 
        inputProps={inputProps2} 
        ref="dropoffVehicle" 
        value={this.state.destination} 
        onChange={this.handledropoffVehicle} />
 </div> );

and then if he has done inputting or the focus is out then the field show it again.


Solution

  • The simplest fix is:

    constructor(props) {
      super(props);
      this.state = {data: true}; 
    }
    
    onClick() {
      this.setState({ data : false} );
    }
    
    render() {
      const elements = (
        <div>
          <label>Pick-up</label>
          <PlacesAutocomplete 
            inputProps={inputProps} 
            ref="pickupVehicle" 
            value={this.state.pickup} 
            onChange={this.handlepickupVehicle} 
            onClick={this.onClick.bind(this)} />
       </div>
       {this.state.data &&
         <div>
           <label>Drop-off</label>   
           <PlacesAutocomplete 
             inputProps={inputProps2} 
             ref="dropoffVehicle" 
             value={this.state.destination} 
             onChange={this.handledropoffVehicle} />
         </div> 
        }
      );
    
      return elements;
    }
    

    There's some points to be noticed:

    • binding the onClick function (so that the "this" can be used): this.onClick.bind(this)

    • use {this.state.data && [JSX] } for conditionally show/hide element block by its state

    If you have further issues, please post here so we can get through together!