onTouchTap with Material-UI
Material-UI is a set of React components that was developed in 2014 out of a love for React and Google’s Material Design. Because it was developed with React in mind, it is quite easy for people who are more familiar with React to hit the ground running in designing their front-end. However, there are quirks that even those who are familiar with React will need to get adjusted to. One of those is the property onTouchTap provided by react-tap-event-plugin as the official event listener for Material-UI components, thereby replacing familiar event listeners such as onClick and onSubmit.
First things first is why reinvent the wheel? If onClick and onSubmit seem to work fine, then why do we need onTouchTap? Material-UI reasons that onClick and onSubmit are not fast enough due to a 300ms latency, which may cause certain events to not be registered or triggered in your application, especially when React was built with speed in mind.
If you’re wondering why you cannot just implement onTouchTap in Material-UI, it is because there is some setup required with onTouchTap since it is not included in the Material-UI npm package, but is rather a part of react-tap-event-plugin.
To get started with onTouchTap, you first have to run
npm install react-tap-event-plugin
then you require it in your highest React component,
import injectTapEventPlugin from 'react-tap-event-plugin';
// both is needed for onTouchTap
Now say you want to import some sort of button from Material-UI and implement that component in your UI design. Rather than maybe having <forms> and <inputs> with a type of submit and an onSubmit method on the form, you will be using <Button>, a Material-UI component that has a property known as onTouchTap. Whereas onClick and onSubmit methods need to take in a parameter, most commonly named as ‘e’ which stands for element, onTouchTap does not.
Above is an example of implementing onTouchTap with Material-UI’s RaisedButton component in a barter application written in React/React-Router. If you look at the <RaisedButton/> JSX component, onTouchTap will invoke addPost which makes an axios post request to my API.