Categories
React Answers

How to Combine Multiple Inline Style Objects in React?

Spread the love

Sometimes, we want to combine multiple inline style objects in React.

In this article, we’ll look at how to combine multiple inline style objects in React.

Combine Multiple Inline Style Objects in React

We can use the spread operator to combine multiple inline style objects in React.

For instance, we can write:

import React from "react";

const baseStyle = {
  color: "red"
};

const enhancedStyle = {
  fontSize: "38px"
};

export default function App() {
  return <h1 style={{ ...baseStyle, ...enhancedStyle }}>hello world</h1>;
}

to combine the inline styles from the baseStyle and enhancedStyle objects with the spread operator.

The style properties are spread into a new object which is passed in as the value of the style prop.

Therefore, we should see red text in 38 point size font displayed.

Conclusion

We can use the spread operator to combine multiple inline style objects in React.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *