React Tips — Detect KeyPress, Unique IDs, and Remove Items

John Au-Yeung
4 min readJul 28, 2020
Photo by Quinn Buffing on Unsplash

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Generate Unique IDs for Form Labels in React

We can generate unique IDs with the Lodash or Underscpre’s uniqueId method.

For instance, we can write:

class App extends React.Component {
constructor(props) {
super(props);
this.id = _.uniqueId("form-");
}

render() {
const id = this.id;
return (
<div>
<input id={id} type="text" />
<label htmlFor={id}>label</label>
</div>
);
}
}

We called uniqueId and assigned the returned value as the value of the id prop.

The argument for the method is the prefix for the ID.

With function components, we can write:

import React, { useState } from 'react';
import uniqueId from 'lodash/uniqueId';
const App = (props) => {
const [id] = useState(uniqueId('form-'));
return (
<div>
<input id={id} type="text" />
<label htmlFor={id}>label</label>
</div>
);
}

We imported the uniqueId function and then put it in useState .

This way, we can get the ID as variable and use it in our form child elements.

Detect Esc Key Press in React

We can detect the Esc key by adding a keydown event handler into our component.

For instance, we can write:

class Page extends React.Component {
constructor(props){
super(props);
this.onKeyPress = this.onKeyPress.bind(this);
}
onKeyPress(event){
if(event.keyCode === 27) {
//...
}
}
componentDidMount(){
document.addEventListener("keydown", this.onKeyPress, false);
}
componentWillUnmount(){
document.removeEventListener("keydown", this.onKeyPress, false);
}
render(){
return (
<input />
)
}
}

--

--