In this video we’ll show you how to clean up any inline styling for Gutenberg blocks using the javascript spread syntax. We’re building Gutenberg blocks for a WordPress theme and we want to give the user control over some CSS properties like padding, border-radius, etc. Padding alone has four different properties that you’d want to have the ability to change: padding-top, padding-left, padding-bottom, and padding-right. So things can get a little unwieldy pretty quickly.
Thank goodness for the Javascript spread syntax. Since Gutenberg blocks are using React and written in Javascript we can pretty easily employ the spread syntax for managing lots of inline styling.
For example, imagine you have some inline padding styles you want to apply to some html in a Gutenberg block, or React component, and you’re using JSX syntax. JSX accepts inline styles as an object like below:
<div style={{ paddingTop: '10px', paddingRight: '10px', paddingBottom:'10px', paddingLeft: '10px' }}}></div>
So we can just pull out this object and then use the spread syntax to expand that style into the div’s style attribute object:
const paddingStyles = { paddingTop: '10px', paddingRight: '10px', paddingBottom:'10px', paddingLeft: '10px' };
<div style={{ ...paddingStyles }}></div>
It gets really easy to expand this pattern with other CSS properties as well:
const paddingStyles = { paddingTop: '10px', paddingRight: '10px', paddingBottom:'10px', paddingLeft: '10px' };
const marginStyles = { marginTop: '5px', marginRight: '5px', marginBottom:'5px', marginLeft: '5px' };
<div style={{ ...paddingStyles, ...marginStyles }}></div>
Keep in mind you DO need the double curly brackets on the style attribute because you are expanding, or spreading, those CSS property objects (marginStyles, paddingStyles) into the object that the style attribute accepts.
Finally, you can mix the spread syntax with inline styling as well, like so:
const paddingStyles = { paddingTop: '10px', paddingRight: '10px', paddingBottom:'10px', paddingLeft: '10px' };
const marginStyles = { marginTop: '5px', marginRight: '5px', marginBottom:'5px', marginLeft: '5px' };
<div style={{ ...paddingStyles, ...marginStyles, border:'5px solid #000000', borderRadius:'3px' }}></div>