1

How to recognize if User chose data by either pressing "Enter" button or by mouse click?

Below is my code:

<SingleDatePicker
    date={this.state.date}
    isOutsideRange={() => false}
    isDayHighlighted={day => isSameDay(moment(new Date()),moment(day))}
    daySize={30}
    verticalSpacing={2}
    onDateChange={date => {
        this.setState({ date });
        if(date) {
            this.props.onSaveValue(date.unix());
        }
    }}
    displayFormat={this.props.dateFormat}
    focused={this.state.focused}
    numberOfMonths={1}
    placeholder={this.props.dateFormat}
    onFocusChange={({ focused }) =>{
        this.setState({ focused });
        this.props.isCalendarOpen(focused)
    }}
/>

I have simple SingleDatePicker and I didn't find some way to recognize how User chose data, without addeventlisener and other listeners.

Ankur Soni
  • 5,725
  • 5
  • 50
  • 81
Andre Voks
  • 31
  • 4

1 Answers1

1

As per SyntheticEvent Documentation for ReactJS,

  1. To identify if Enter is hit you can use onChange method call on input.
  2. To identify mouse event, you can use onClick to identify the click event. So the code shall look as below;

    constructor(props) {
        super(props);
        this.handleEvent = this.handleCommonEvent.bind(this);
    }
    
    handleCommonEvent: function(e) {
        if(e.nativeEvent 
           && e.nativeEvent.type 
           && e.nativeEvent.type == 'click'){
             // do something here on mouse click
        } else if(e.nativeEvent 
           && e.nativeEvent.type 
           && e.nativeEvent.type == 'input'){
           // do something here on keyboard input
        }
    
    }
    

In your input field add below stuff as well.

<...onClick={ this.handleEvent } onChange={ this.handleEvent }..../>

NOTE: e is a synthetic event. React defines these synthetic events according to the W3C spec, so you don’t need to worry about cross-browser compatibility.

Ankur Soni
  • 5,725
  • 5
  • 50
  • 81