Last updated: Apr 7, 2024
Reading time·2 min
To set a box-shadow in React:
style
prop on the element.boxShadow
property to add a shadow effect around the element's
frame.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;
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.
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.
<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.
.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.
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 run.
On the other hand, if you import a CSS file into a component, the CSS styles might get removed once your component unmounts.