I am creating multiple counters on click and I want to connect the two counters, When I increase the value in the first counter it should automatically decrease in the second counter. Can you suggest any solution where I can communicate with multiple counters as I can generate multiple counters on click?
const Counter = ({ value, onIncrement, onDecrement, hideIncrement }) => {
return (
<div>
<span>{value}</span>
{value > 0 && (
<button
onClick={() => {
onDecrement();
}}
>
-
</button>
)}
{hideIncrement === false && value < 10 && (
<button
onClick={() => {
onIncrement();
}}
>
+
</button>
)}
</div>
);
};
const Counters = () => {
const [counters, setCounters] = React.useState([4, 0, 0, 5]);
const sum = counters.reduce((acc, item) => acc + item, 0);
return (
<div>
<p>Sum: {sum}</p>
<button
onClick={() => {
setCounters([...counters, 0]);
}}
>
Add counter
</button>
<br />
<div>
{counters.map((value, index) => (
<Counter
value={value}
hideIncrement={sum >= 20}
onIncrement={() => {
const countersCopy = [...counters];
countersCopy[index] += 1;
setCounters(countersCopy);
}}
onDecrement={() => {
const countersCopy = [...counters];
countersCopy[index] -= 1;
setCounters(countersCopy);
}}
/>
))}
</div>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<Counters />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
You can pass state to Couter component: try this:
const Counter = ({value, onIncrement, onDecrement, hideIncrement,
addStatus, counterIndex, index}) => {
useEffect(() => {
if (counterIndex === index - 1) onDecrement(addStatus);
}, [counterIndex, addStatus])
return (
<div>
<span>{value}</span>
{value > 0 && (
<button
onClick={() => {
onDecrement();
}}
>
-
</button>
)}
{hideIncrement === false && value < 10 && (
<button
onClick={() => {
onIncrement();
}}
>
+
</button>
)}
</div>
);
};
const Counters = () => {
const [counters, setCounters] = React.useState([4, 4, 4, 5]);
const [addStatus, setAddStatus] = useState(0);
const [counterIndex, setCounterIndex] = useState(0);
const sum = counters.reduce((acc, item) => acc + item, 0);
return (
<div>
<p>Sum: {sum}</p>
<button
onClick={() => {
setCounters([...counters, 0]);
}}
>
Add counter
</button>
<br/>
<div>
{counters.map((value, index) => (
<Counter
value={value}
index={index}
addStatus={addStatus}
counterIndex={counterIndex}
hideIncrement={sum >= 20}
onIncrement={() => {
const countersCopy = [...counters];
countersCopy[index] += 1;
setAddStatus(a => a + 1)
setCounterIndex(index)
setCounters(countersCopy);
}}
onDecrement={() => {
const countersCopy = [...counters];
countersCopy[index] -= 1;
setCounters(countersCopy);
}}
/>
))}
</div>
</div>
);
};