Languages
[Edit]
EN

React - how to move element to front using z-index CSS property

3 points
Created by:
Dirask Community
3960

In this article we would like to show you how to move element to front using zIndex style property (z-index property equivalent in pure CSS).

z-index style property example in React.
z-index style property example in React.

Below example shows two components with different styles:

  • Component1 with zIndex: '1',
  • Component2 with zIndex: '2'.

An element with greater zIndex is always in front of an element with a lower zIndex value, so in our case Component2 (zIndex: '2') covers Component1 (zIndex: '1').

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.

// import React from react';
// import ReactDOM from 'react-dom';

const Component1 = () => {
    const style = {
        position: 'fixed',
        left: '30px',
        top: '10px',
        background: 'goldenrod',
        width: '100px',
        height: '100px',
        zIndex: '1'
    };
    return (
      <div style={style}>
        z-index: 1
      </div>
    );
};

const Component2 = () => {
  	const style = {
        position: 'fixed',
        left: '10px',
        top: '40px',
        background: 'yellow',
        width: '100px',
        height: '100px',
        zIndex: '2'
    };
    return (
      <div style={style}>
        z-index: 2
      </div>
    );
};

const App = () => {
  	const style = {
        height: '120px'
    };
    return (
      <div style={style}>
        <Component1 />
        <Component2 />
      </div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

Note: zIndex only works when element has position set to: fixed, absolute, relative or sticky.

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join