How to set a CSS box-shadow in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# 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

The code for this article is available on GitHub

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

# Set a CSS box-shadow using inline styles

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;

set css box shadow using inline styles

The code for this article is available on GitHub

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.

# Set a CSS box-shadow using an external stylesheet

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;

set css box shadow using external stylesheet

The code for this article is available on GitHub

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 run.

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.