How to set the z-index attribute in React

avatar
Borislav Hadzhiev

Last updated: Jan 18, 2023
2 min

banner

# Set the z-index attribute in React

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.

App.js
const App = () => { return ( <div> <div style={{ position: 'relative', zIndex: '3', backgroundColor: 'salmon', padding: '2rem', }} > bobbyhadz.com </div> </div> ); }; export default App;

set z index attribute in react

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.

App.js
<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.

# Set the z-index attribute using an external CSS file

If you don't want to camelCase CSS properties, write your styles in an external CSS file.

App.css
.z-50 { z-index: 50; position: relative; }

And here is how we would import and use the z-50 class.

App.js
import './App.css'; const App = () => { return ( <div> <div className="z-50">Hello world</div> </div> ); }; export default App;

set z index attribute using external css file

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.