Sunday, August 6, 2017

React datetime component, disable keyboard input

We currently use react on our current project and react-datetime library to render datetime picker.



Recently we got a requirment to disable keyboard input, so that users can choose a date only from the calendar UI. Unfortunately this functionality is not availbale out of the box. But there is a way to do it.

ReactDOM package provides a method to locate html element that contains react component.

ReactDOM.findDOMNode(this);

The simplest solution would be to wrap <Datetime /> component with a custom one and then disable user input, simply suppress all keyboard interaction.

Each react component has a set of hooks , one of them is componentDidMount. This method is invoked once when component is mounted. This is the right place to do some magic.

componentDidMount() {
  const componentPlaceholder = ReactDOM.findDOMNode(this);
  $(componentPlaceholder)
   .find('input')
   .on('keydown', () => false);
}

We simply search for the html element that contains the component and then search for an input inside of that element. Then we add event listenet for keydown event and suppres all keys. It would probably make sense to add some exceptions for some special keys like F11, F12, etc.

Full component code:


import React from 'react';
import ReactDOM from 'react-dom';
import Datetime from 'react-datetime';
import 'react-datetime/css/react-datetime.css';

export default class DateTimePicker extends React.Component {

    componentDidMount() {
      const componentPlaceholder = ReactDOM.findDOMNode(this);
      $(componentPlaceholder)
          .find('input')
          .on('keydown', () => false);
    }

    render() {
        return <Datetime {...this.props} />;
    }
}

No comments:

Post a Comment