I made this React application with typescript for practicing. It contains a counter. Small circles supposed to be indicate the tens, while big ones the hundreds of counter.
This is my code:
`
import {useEffect, useState} from 'react';
export default function Counter(props: { startCount: number }): JSX.Element {
const [result, setResult] = useState<number>(props.startCount);
const [extraElementArray, setExtraElementArray] = useState<Array<JSX.Element>>([]);
const tenElement: JSX.Element = <div className='extra-element--ten'>O</div>;
const hundredElement: JSX.Element = <div className='extra-element--hundred'>O</div>;
const handleClick = (amount: number) => {
setResult(prevResult => prevResult + amount);
}
useEffect(
() =>
setExtraElementArray(() => {
let resArray: Array<JSX.Element> = [];
for (let i = 1; i <= Math.floor(result / 100); i++) {
resArray.push(hundredElement);
}
for (let i = 0; i < Math.floor(result / 10) % 10; i++) {
resArray.push(tenElement);
}
return resArray;
}), [result]);
return (
<>
<div className='counter-container'>
<div className='minus-button' onClick={() => handleClick(-1)}>-</div>
<div className='result-display'>{result}</div>
<div className='plus-button' onClick={() => handleClick(1)}>+
</div>
</div>
<div className='extra-element-container'>
{extraElementArray}
</div>
</>
);
}
`
I used two for cycles that works perfectly but I affraid this is not the best neither the most elegant approach.
I've tried out the solution that is recommended in all of the topics with similar problems e.g. tihs one link, but Array(number).fill(element) didn't work for me since the calcualted number that initialize the array can be zero.
I'm wondering if there is a solution javascript / typescript that repeat an array element n times and concat to the array. Something like this: array.pushRepeat(element, n). If n = 0 gives an empty array