I’m making a Cookie-type clicker. But I ran into such a problem that the pop-up element simply does not appear. Here is the code:
Caravan.tsx
interface CaravanProps{
x: number;
y:number;
}
function randomNumberBetween(min: number, max: number): number {
return Math.random() * (max - min) + min;
}
export let CaravanGen = () => {
let caravanList: Array<JSX.Element> = new Array<JSX.Element>();
const[carList, setCarList] = useState(caravanList);
useEffect(() => {
let timer = randomNumberBetween(3000, 6000);
let newCarList = carList;
const interval = setInterval(() => {
const x = randomNumberBetween(0, 1900);
const y = randomNumberBetween(0, 1000);
newCarList.push(<Caravan x={x} y={y}/>);
setCarList(newCarList);
console.log(x, y);
}, timer);
return () => {
clearInterval(interval);
};
}, []);
return(<div className='caravan-gen'>{caravanList}</div>);
}
export function Caravan(props: CaravanProps) {
return(
<div style={{
position: 'absolute',
left: props.x,
top: props.y,
width: "100px",
height: "100px",
borderRadius: "100%",
backgroundColor: "black"
}}>
</div>
);
}
index.css
.caravan-pop{
width: 100px;
height: 100px;
border-radius: 100%;
background-color: black;
z-index: 10;
}
In Coockie Clicker A golden cookie appears in it at random intervals, which gives some bonuses. I want to implement the same thing so that my element appears in a random place on the screen and when I click on it, something will happen.
2
Answers
Fixed it.
The problem was that when changing the array with JSX elements, the page was not updated. I have been studying React for no more than 3 months and my ignorance of working with webhooks affected here. To fix it, I left
carList
andsetCarList
. In the interval recorded a webhook:Here is the corrected code.
And a screenshot of the result I needed. See screenshot
The problem
Your
useEffect
hook call has no dependencies. Which means it will only run intially once and stops.Possible solution
Add
carList
into the dependency array. This might be the issue.Hope this helps! Otherwise just comment below for more input.