1

I can't figure out why React is not updating the style on the Div as it's updating the style opacity with a timeout event.

import React from 'react'

function PortItem(props){

  let style = {
      opacity: 0
  };

  setTimeout(function(){style = {opacity: 1};},3000);
  
  return(
    <div className="portItem" style={style} onClick={()=>props.click(props.pitem.id)}>
      <img src={props.pitem.src} alt={props.pitem.title}></img>
    </div>
  )
}

export default PortItem

2 Answers 2

2
import React, { useState, useEffect } from "react";

function PortItem(props) {
  const [style, setStyle] = useState({ opacity: 0 });

  useEffect(() => {
    setTimeout(function () {
      setStyle({ opacity: 1 });
    }, 3000);
  }, []);

  return (
    <div
      className="portItem"
      style={style}
      onClick={() => props.click(props.pitem.id)}
    >
      <img src={props.pitem.src} alt={props.pitem.title}></img>
    </div>
  );
}

export default PortItem;

Sign up to request clarification or add additional context in comments.

Comments

1

move the style to the state or a ref, so the component would rerender when it changes.

const [style, setStyle] = useState({ opacity: 0 });
setTimeout(function(){setStyle({ opacity: 1 })};},3000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.