M
M
MarEeeeeee2021-04-19 16:50:37
React
MarEeeeeee, 2021-04-19 16:50:37

How to change Z-index with a delay of 5 seconds?

It is required to change the z-index of this block after a certain period of time. Why doesn't my version work? How to implement more correctly?

export default function(){
    const timerRef = useRef(null);

    const changeIndex = () => {
        const style = {zIndex:30000}
        timerRef.current = setTimeout(()=>{
            console.log(styles)
        },1000)
    }



    return(       
            <header className={styles.header + " navbar navbar-expand-lg navbar-light sticky-top " } style = {{changeIndex}}></header>
)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Klein Maximus, 2021-04-19
@kleinmaximus

import React, { useEffect, useState } from 'react';

// Функция-инициализатор нужна, чтобы вынести создание объекта состояния из компонента
const initStyle = () => ({ zIndex: 0 });

const Component = () => {
  const [style, setStyle] = useState(initStyle);

  useEffect(() => {
    // Вот здесь можно менять значения - zIndex поменяется через секунду
    const timer = setTimeout(() => setStyle({ zIndex: 1 }), 1000);

    // Надо не забыть почистить счетчик setTimeout
    return () => clearTimeout(timer);
  }, []);

  return <header className={`${styles.header} navbar navbar-expand-lg navbar-light sticky-top`} style={style} />
};

Can be done differently
import React, { useEffect, useMemo, useState } from 'react';

const Component = () => {
  const [zIndex, setZIndex] = useState(0);

  // Поскольку style это объект, то неплохо бы его мемоизировать
  const style = useMemo(() => ({ zIndex }), [zIndex]);

  useEffect(() => {
    const timer = setTimeout(() => setZIndex(1), 1000);

    return () => clearTimeout(timer);
  }, []);

  return <header className={`${styles.header} navbar navbar-expand-lg navbar-light sticky-top`} style={style} />
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question