Last updated: Apr 7, 2024
Reading time·2 min
To set the z-index attribute on an element in React, set the style
prop on
the element and use the zIndex
property, e.g. style={{zIndex: '3'}}
.
The z-index CSS property influences the way HTML elements stack on top of one another.
const App = () => { return ( <div> <div style={{ position: 'relative', zIndex: '3', backgroundColor: 'salmon', padding: '2rem', }} > bobbyhadz.com </div> </div> ); }; export default App;
We set the z-index
of the element by using the zIndex
property in the element's style object.
Multi-word property names are camelCased in the object we pass to the style
prop in React, e.g. backgroundColor
and zIndex
.
Notice that we used 2 sets of curly braces when setting the style
prop on the
element.
<div style={{ position: 'relative', zIndex: '3', backgroundColor: 'salmon', padding: '2rem', }} > bobbyhadz.com </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.
If you don't want to camelCase CSS properties, write your styles in an external CSS file.
.z-50 { z-index: 50; position: relative; }
And here is how we would import and use the z-50
class.
import './App.css'; const App = () => { return ( <div> <div className="z-50">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 run.
On the other hand, if you import a CSS file into a component, the CSS styles might get removed once your component unmounts.
You can learn more about the related topics by checking out the following tutorials: