In React it's very common to pass multiple props to the component. So it's no wonder that many of the React component functions interact with few or more props.
Class Component
For example, if we have simple component, which in render
function uses 4 different props.
import React from "react";
class Row extends React.Component {
state = {
showEmail: false
};
render() {
return (
<div>
<div>
<span>First Name: {this.props.firstName}</span>
</div>
<div>
<span>Last Name: {this.props.lastName}</span>
</div>
{this.state.showEmail && (
<div>
<span>Email: {this.props.email}</span>
</div>
)}
<button onClick={this.props.doSomethingAmazing}>Click me</button>
</div>
);
}
}
We could apply ES6 destructuring assignment to simplify code.
import React from "react";
class Row extends React.Component {
state = {
showEmail: false
};
render() {
const { firstName, lastName, email, doSomethingAmazing } = this.props;
return (
<div>
<div>
<span>First Name: {firstName}</span>
</div>
<div>
<span>Last Name: {lastName}</span>
</div>
{this.state.showEmail && (
<div>
<span>Email: {email}</span>
</div>
)}
<button onClick={doSomethingAmazing}>Click me</button>
</div>
);
}
}
Note: I didn't destruct showEmail
variable because in the render
function I am only using one property one time from state
.
In my mind function like this
showAlert(){
alert(this.state.showEmail)
}
reads more easily than
showAlert(){
const { showEmail } = this.state;
alert(showEmail);
}
Especially if there is a lot of code between destructing and variable usage. Though I would destruct variable if I want to use one prop for it more than one time.
showAlert(){
const { showEmail } = this.state;
alert(showEmail);
alert(showEmail);
}
Function component
The benefits of ES6 destructuring assignment looks even nicer in the function component.
If we would have a similar component without a state:
import React from "react";
const Row = props => (
<div>
<div>
<span>First Name: {props.firstName}</span>
</div>
<div>
<span>Last Name: {props.lastName}</span>
</div>
<div>
<span>Email: {props.email}</span>
</div>
<button onClick={props.doSomethingAmazing}>Click me</button>
</div>
);
Applying props destructuring technique allows to write code like this:
import React from "react";
const Row = ({ firstName, lastName, email, doSomethingAmazing }) => (
<div>
<div>
<span>First Name: {firstName}</span>
</div>
<div>
<span>Last Name: {lastName}</span>
</div>
<div>
<span>Email: {email}</span>
</div>
<button onClick={doSomethingAmazing}>Click me</button>
</div>
);
Isn't that neat!
Top comments (0)