Inline React Styles Using the JSX Spread Operator
Background
This article shows you one of the many ways to modularize and reuse inline styles for React using Plain Old Javascript Objects with the help of the React statics
object and the JSX Spread Operator.
statics
Object
As per the React Component Specs and Lifecycle documentation, the statics
object allows you to define static methods [and properties] that can be called on the component class.
What this means is that you can access these properties of your React component class outside of instantiation of the actual component.
For example, let’s say we have the following React component:
We will then have access to MyComponent#customMethod
anywhere within our application where MyComponent
is defined (via import or require).
JSX Spread Operator
Based on the ES2015 (ES6) Spread Operator for arrays and function calls, the JSX Spread Operator brings the same goodness to objects.
What this means is that we can create new objects based on old ones while adding or overriding properties on the previous one.
Suppose we have an object in our code like:
If we ever want to create a new object based on this one (as opposed to mutating it, for the purposes of using this object as our State in something like a Redux store), we can then define a new object using:
This would result in a newContact
object with the value of:
How Can I Apply This to Inline Styles in React?
As an example, we’ll be using a React component called Person
that is the parent component wrapping a component called PersonSummary
.
What’s happening here is that the styles
property of the PersonSummary
component is being defined as the value of Person.styles
(a static property that is available anywhere) with the addition of the color
property, containing the value of white
.
Our PersonSummary styles
object will contain the following styles when it is rendered:
The rendered Person component will look something like this:
After Action Review
We covered one of many (and seemingly controversial) techniques used to implement reusable styles in React components. Personally, I think inline styling via Plain Old Javascript Objects seems to be the way to go.
By factoring style objects out into ES6 modules and recycling common CSS properties using the JSX Spread Operator as a sort of mixin seems like it would result in fairly clean and readable React components in your projects as they scale up in size.