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 />
)
}
}
We add an event listener for the keydown
event by calling documebnt.addEventListener
in the componentDidMount
method.
This will ensure that the event listener is added when the component mounts.
Likewise, we can removeEventListener
to remove the event listener to ensure that it’s unloaded when the component unmounts.
this.onKeypress
is the event handler.
In the method, we check the keyCode
property to get the code for the key pressed.
27 is the code for the Esc key.
With function components, we can use the useEffect
hook to add and remove the listener.
For instance, we can write:
import React, { useEffect } from 'react';
const App = () => {
useEffect(() => {
const handleEsc = (event) => {
if (event.keyCode === 27) {
console.log('Close')
}
};
window.addEventListener('keydown', handleEsc);
return () => {
window.removeEventListener('keydown', handleEsc);
};
}, []);
return(<p><input /></p>);
}
We have the useEffect
hook with a callback to add the keydown
listener.
We call addEventListener
when the component mounts with addEventListener
.
The empty array in the 2nd argument ensure that it loads only when the component mounts,
We call removeEventListener
when the component unmounts to remove the listener when it unmounts.
The event listener code is the same as the previous example.
Delete Item from State Array in React
We can delete an item from a state array by calling splice
on the original array and then calling setState
to set that as the new value of the state array.
For instance, we can write:
removePeople(e) {
const people = [...this.state.people];
const index = array.indexOf(e.target.value);
if (index !== -1) {
people.splice(index, 1);
this.setState({ people });
}
},
First, we make a copy of the array so that we can modify it without changing the original array.
Then we get the index that we want to remove.
Then we call splice
to remove the item from the array copy.
And then we call setState
to set that as the new value.
We can also use the filter
method to return a new array that includes the items that we want to keep.
For example, we can write:
class ItemsList extends Component {
constructor() {
this.state = {
itemsList: [
{
id: 1,
name: 'All Items',
}, {
id: 2,
name: 'In Stock Items',
}
],
}
this.removeItem = this.removeItem.bind(this)
}
removeItem(deleteItemId) {
this.setState({
itemsList: this.state.itemsList.filter(item => item.id != deleteItemId)
})
}
render(){
return <div />
}
}
We called filter
to return a new array that includes only the items with id
value other than deleteItemId
.
Then we call setState
to set that as the new value of itemsList
state.
Conclusion
We can generate unique ID with Underscore or Lodash methods.
There are a few ways to remove an item from a state array.
And there are multiple ways to detect Esc key press.