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.
Sort an Array of Objects in React and Render Them
We can sort an array of objects with the sort
method.
Then we can call map
to render the sorted entries.
For instance, in the render
method or function component, we may write:
const myData = this.state.data
.sort((a, b) => a.name > b.name ? 1 : -1)
.map((item) => (
<div key={item.id}> {item.name}</div>
));
We call the sort
method sort the data by the name
property.
We check if a.name > b.name
is true
.
Strings can be compared directly.
Use onClick with divs in React
We can use onClick
with divs if we provide it a size.
For instance, we can write:
class App extends React.component {
constructor() {
this.state = {
color: 'black'
};
},
changeColor() {
const newColor = this.state.color == 'white' ? 'black' : 'white';
this.setState({
color: newColor
});
},
render() {
return (
<div>
<div
style = {{
background: this.state.color,
width: 100,
height: 100
}}
onClick = {this.changeColor}
>
</div>
</div>
);
}
}
We create a div with a background by passing in an object with the styles in the style
prop.
We set the width
and height
to 100px so that we can display a div with nothing inside.
Then we can pass in a click handler to the onClick
prop.
In the changeColor
method, we just toggle between white and black for the color
state.
Add a <br> Tag in React Between Two Strings
We can add a line break character in a string to add a line break.
Then we can use the white-space: pre-line
style to make them display.
For instance, we can write:
render() {
message = `Hello n World.`;
return (
<div className='new-line'>{message}</div>
);
}
in our component.
Then we can add the following CSS:
.new-line {
white-space: pre-line;
}
Clearing an Input Value After Form Submit in a React Component
We can clear an input value after form submit in a React component.
To do that, we write:
onHandleSubmit(e) {
e.preventDefault();
const name = this.state.name;
this.props.searchByName(name);
this.setState({
name: ''
});
}
We call preventDefault
to stop the default submit behavior.
Then we get the name
from the state
which is what we inputted.
Then we call our search function.
And finally, we clear the input value by clearing the name
state by assigning it an empty string.
Edit Multiple Input Controlled Components in React
We can edit multiple, input controlled components by providing their own change handlers.
For instance, we can write:
class Form extends React.Component {
constructor() {
this.state = {};
}
changeFirstName(event) {
const contact = this.state.contact;
contact.firstName = event.target.value;
this.setState({ contact });
}
changeLastName(event) {
const contact = this.state.contact;
contact.lastName = event.target.value;
this.setState({ contact });
}
changePhone(event) {
const contact = this.state.contact;
contact.phone = event.target.value;
this.setState({ contact });
}
render() {
return (
<div>
<input type="text" onChange={this.changeFirstName.bind(this)} value={this.state.contact.firstName}/>
<input type="text" onChange={this.changeLastName.bind(this)} value={this.state.contact.lastName}/>
<input type="text" onChange={this.changePhone.bind(this)} value={this.state.contact.phone}/>
</div>
);
}
}
We have 3 inputs, one for the first name, one for the last name, and one for the phone number.
Then in each handler, we get the values with event.target.value
and then assign it to the state.
Each handler is passed into the onChange
prop of each input.
We’ve to call bind(this)
to return a function that has the component instance as the value of this
.
value
is set to the state that the event handler change.
This way, the inputted values will be displayed.
A better way to do it is to set the name dynamically with computed property keys.
For example, we can write:
class Form extends React.Component {
constructor() {
this.state = {};
}
handleChange(propertyName, event) {
const contact = this.state.contact;
contact[propertyName] = event.target.value;
this.setState({ contact: contact });
}
render() {
return (
<div>
<input type="text" onChange={this.handleChange.bind(this, 'firstName')} value={this.state.contact.firstName}/>
<input type="text" onChange={this.handleChange.bind(this, 'lastName')} value={this.state.contact.lastName}/>
<input type="text" onChange={this.handleChange.bind(this, 'phone')} value={this.state.contact.phone}/>
</div>
);
}
}
We have one change handler for all 3 inputs.
Then we can pass in the field as the 2nd argument of bind
to set that as the first argument of the handler.
Conclusion
We can add change handlers for each input so that we can update their inputted values as the new state values.
We can sort arrays and render them.
Also, we can make empty divs clickable if we set a size for it.