How to set the z-index attribute in React


Borislav Hadzhiev

Sun May 01 20222 min read

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.

const App = () => { return ( <div> <div style={{ position: 'relative', zIndex: '3', backgroundColor: 'salmon', padding: '2rem', }} > Hello world </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.

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, you can write your styles in a 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 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.