Blog

5 Great Uses of the Spread Operator in a React App

5 Great Uses of the Spread Operator in a React App

React has quickly become one of DMC’s favorite tools for web front-end development due to its component-based structure and growing adoption. However, between the JSX syntax, component lifecycle, and state management, learning to use React effectively sometimes feels like learning a language in and of itself.

JavaScript’s spread operator sees a lot of use in DMC’s React applications due to its concision and versatility. Here are 5 of our favorite uses of the spread operator (…) in a React application.
 

1. Passing props
 

Probably the most common usage of the spread operator in a React app is in passing props down to a child component. So long as the object you’re spreading includes all the properties the child component requires, the child component will use those and ignore the extraneous ones.

This allows for much more concise code than breaking out each property that the child inherits from the parent. Note: we use Typescript in our applications, and these examples will use it as well for clarity.

interface LabeledButtonProps extends ButtonProps {
    labelText: string;
}

const LabeledButton = (props: LabeledButtonProps) => (
    <div>
        {props.labelText}
        <Button {...props} />
    </div>
);


2. Generating multiple component instances with common props
 

If you have multiple component instances with some attributes in common, and others which differ, it can be helpful to pull them out into one object which is referenced by all instances. For example, instead of the following:

render () {
    return (
        <div>
            <Button height={20} width={40} color="red" text="Press Here"/>
            <Button height={20} width={40} color="red" text="Or Here!"/>
            <Button height={20} width={40} color="red" text="(Even Here)"/>
        </div>
    );
}

You can instead abstract the common props:

render () {
    let commonButtonAttributes: PartialButtonProps = {
        height: 20, width: 40, color: 'red'
    }
    return (
        <div>
            <Button {...commonButtonAttributes} text="Press Here"/>
            <Button {...commonButtonAttributes} text="Or Here!"/>
            <Button {...commonButtonAttributes} text="(Even Here)"/>
        </div>
    );
}

Similarly, you can map a function which generates an instance of the component using these common props over an array of the unique elements (shown in example 4), which is preferable for longer or dynamic element lists.
 

3. Setting the state with dynamic key name
 

Leaving our button for a moment, another place where we frequently use the spread operator is in functions to handle change events for forms. We typically use the same function to handle changes for all fields in a form, to minimize code repetition.

The following syntax allows setting a property in the state with a dynamic key name while maintaining the other properties previously in the state:

handleChange(name: string, value: string | number) {
    this.setState({ ...this.state, [name]: value });
}

As a note, this pattern is not necessary if using React without using Typescript. This is also a good point to emphasize the importance of order when using the spread operator. I like to think of the spread operator as literally spreading out (in order) the items in an object or list.

If you’re trying to overwrite an existing property, as I am in this case, it’s important to make sure it’s after the spread operator, or the existing property will overwrite your new value!
 

4. Adding a single item to the start or the end of an array
 

The spread operator can also be used working with arrays, which can be very useful in a React application. One situation we encounter frequently is adding an element to an array which is subsequently mapped and rendered. Doing so with the spread operator is simpler and cleaner than doing so with Javascript’s push() or concat().

For example, if our button list always needs to include a cancel button, we could do the following:

const ButtonList = (buttonTexts: string[]) =>
    [...buttonTexts, 'Cancel'].map((buttonText, index) =>
        <Button
            key={index}
            text={buttonText}
            {...commonButtonAttributes}
        />
    );


5. Stripping properties using destructuring
 

Our final favorite use of the spread operator is to strip properties from an existing object to make a new object without setting properties individually. We’ve found this most useful when making calls to an API, when we want to be careful to send only the data we intend.

Specifying all the properties we want on the new object can be quite verbose:

let locationUpdate = {
    name: this.state.name,
    address: this.state.address,
    locationId: this.state.locationId,
    etc…
}

Instead, by using destructuring with the rest syntax, we can specify the properties we want to exclude from the new object.

let { isLoading, availableLocations, ...locationUpdate } = this.state;


Conclusion


Javascript’s spread operator is a powerful tool to minimize boilerplate in a React application and make it easy to read and maintain in addition to its natural performance benefits.

If you’re interested in working with DMC on a React application, feel free to contact us.

Comments

There are currently no comments, be the first to post one.

Post a comment

Name (required)

Email (required)

CAPTCHA image
Enter the code shown above:

Related Blog Posts