Every time I press a button, the same picture has to be rendered in the DOM. This picture should have a random top
value position every time it renders.
I am using Math.random()
but the initial random number doesn't change. For example, if I refresh the page and I get 30 as random number, this number will be the same for each picture
Here is what I have tried:
let top = Math.floor(Math.random()*50)
const ChipStyles = {
position: 'absolute',
top: top,
left: '50%',
transform: 'translate(-50%, -50%)'
}
const Image = () => {
return (
<img src={myImg} style={ChipStyles} alt="" />
)
}
export default Image
With your current set up, your top
value will always be the same, no matter how many Image components you create. If you want a different top value, then you will need to generate a new top value for every Image component. You can do so using the below code.
import React, { useRef } from 'react';
const Image = () => {
const ChipStyles = useRef({
position: 'absolute',
top: Math.floor(Math.random()*50),
left: '50%',
transform: 'translate(-50%, -50%)'
});
return (
<img src={myImg} style={ChipStyles.current} alt=""}/>
)
}
export default Image
This example uses the Ref object, which stores the value on its current
property. Refs will not change from one render to the next, whereas a regular object would.
According to their documentation:
This works because useRef() creates a plain JavaScript object. The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render.
See Reactjs useRef from their official documentation for more information.
EDIT
This originally used useMemo
, however as Adam pointed out, useMemo is not as reliable and is better for performance optimizations rather than storing values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With