'React Transition Group - i dont understand it well
I'm trying to make an array of images that changes image every few seconds.
I made it change randomly and now I'm trying to add transition so it so it will look prettier.
The only way I saw it's being possible with React is using react-transition-group.
so I have made this useEffect:
const [imageSrc, setImageSrc] = useState(image1);
const inProp = useRef(true);
const defaultStyle = {
transition: `opacity 2s ease-in-out`,
opacity: 0,
};
const transitionStyles = {
entering: { opacity: 1 },
entered: { opacity: 1 },
exiting: { opacity: 0 },
exited: { opacity: 0 },
};
useEffect(() => {
const changeImage = () => {
const imagesArr = [image1, image2, image3];
const imagesLength = imagesArr.length;
let random = Math.floor(Math.random() * imagesLength);
setImageSrc(imagesArr[random]);
inProp.current = !inProp.current;
};
setInterval(changeImage, 6000);
return () => {
clearInterval(changeImage);
};
}, []);
<Transition in={inProp.current} timeout={300}>
{(state) => (
<img
src={imageSrc}
alt="about-img"
className="about-img"
style={{
...defaultStyle,
...transitionStyles[state],
}}
/>
)}
</Transition>
also I get this kind of error:
so what happens now it makes transition but not the way I want it. I want to make the transition on every change of image. maybe you guys can please help me? Thanks alot !
Solution 1:[1]
It is probable that you are using React.StrictMode. Here a work-around is presented by the removal of StrictMode, however, that should only be tried if all else fails.
The documentation proposes adding refs. Here we can see an example for it:
import React, { createRef, Component } from "react";
// ChildComponent uses React.forwardRef to obtain the ref passed to it
// and then forward it to the DOM div that it renders.
const ChildComponent = React.forwardRef((props, ref) =>
<div ref={ref}>
<span>{props.children}</span>
</div>
);
class MyComponent extends Component {
componentDidMount() {
const node = this.childRef.current;
/* Uses DOM node */
}
childRef = createRef();
render () {
return (
// Pass the created ref to ChildComponent
<ChildComponent ref={this.childRef}>{this.props.children}</ChildComponent>
);
}
}
export default MyComponent;
So, we:
importcreateRef- instantiate it
- add a
refattribute to the component's markup pointing tothis.childRef
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lajos Arpad |

