How to set a CSS box-shadow in React

avatar

Borislav Hadzhiev

Mon May 02 20222 min read

banner

Photo by Eniko Kis

Set a CSS box-shadow in React #

To set a box-shadow in React:

  1. Set the style prop on the element.
  2. Set the boxShadow property to add a shadow effect around the element's frame.
App.js
const App = () => { const divStyles = { boxShadow: '1px 2px 9px #F4AAB9', margin: '4em', padding: '1em', }; return ( <div> <div style={divStyles}>Hello world</div> </div> ); }; export default App;

react box shadow

We used the boxShadow property on the style object to add a shadow effect around the element's frame.

You could also add the box shadow style inline.

App.js
const App = () => { return ( <div> <div style={{ boxShadow: '1px 2px 9px #F4AAB9', margin: '4em', padding: '1em', }} > Hello world </div> </div> ); }; export default App;

Note that multi-word properties like box-shadow are camelCased when accessed on the style object.

The value of the style property is wrapped in 2 sets of curly braces.

App.js
<div style={{ boxShadow: '1px 2px 9px #F4AAB9', margin: '4em', padding: '1em', }} > Hello world </div>
The first set of curly braces in the inline style marks the beginning of an expression, and the second set of curly braces is the object containing styles and values.

Alternatively, you can write your styles in a file with a .css extension.

App.css
.box-shadow-md { box-shadow: 1px 2px 9px #f4aab9; margin: 4em; padding: 1em; }

And here is how we would import and use the box-shadow-md class.

App.js
import './App.css'; const App = () => { return ( <div> <div className="box-shadow-md">Hello world</div> </div> ); }; export default App;
When importing global CSS files in React, it's a best practice to import the CSS file into your index.js file.

The index.js file is the entry point of your React application, so it's always going to be ran.

On the other hand, if you import a CSS file into a component, the CSS styles might get removed once your component unmounts.

Use the search field on my Home Page to filter through my more than 1,000 articles.