I have a button that adds a new div (onClick). I want to add +1 to cargoNumberCounter so that it shows that it’s a new div.
JavaScript
x
23
23
1
const [addReference, setAddReference] = useState([])
2
const [cargoNumberCounter, setCargoNumberCounter] = useState(1)
3
4
const createNewRef = () => {
5
setCargoNumberCounter(cargoNumberCounter + 1)
6
7
const newRef = (
8
<div>
9
<Heading>
10
Cargo # {cargoNumberCounter}
11
// {cargoNumberCounter.map((num, i) => (
12
// <p key={i}>Cargo # {num}</p>
13
// ))}
14
</Heading>
15
<Button onClick={createNewRef}>
16
Add more cargo
17
</Button>
18
</div>
19
)
20
21
setAddReference((ref) => [ref, newRef])
22
}
23
I thought I could make it work like I have shown in the example, or by spreading the state like so setCargoNumberCounter([...cargoNumberCounter, cargoNumberCounter +1])
, but for some reason it doesn’t work.
Any thoughts on how to add +1 to each new div ?
Advertisement
Answer
It sounds like you may be better off with one button to add new items of cargo to the list. Here’s a quick example.
JavaScript
1
41
41
1
const { useState } = React;
2
3
function Example() {
4
5
// Simple counter in state. You may prefer this to be
6
// an array, or an object that you can add item objects to
7
const [counter, setCounter] = useState(0);
8
9
// Returns an array of divs based on the counter value
10
function getDivs() {
11
const divs = [];
12
for (let i = 0; i < counter; i++) {
13
divs.push(<div>{i + 1}</div>);
14
}
15
return divs;
16
}
17
18
// Updates the counter
19
function handleClick() {
20
setCounter(counter + 1);
21
}
22
23
return (
24
<div>
25
<div className="divs">
26
{getDivs()}
27
</div>
28
<div className="counter">Div count: {counter}</div>
29
<button type="button" onClick={handleClick}>
30
Add new div
31
</button>
32
</div>
33
);
34
35
}
36
37
38
ReactDOM.render(
39
<Example />,
40
document.getElementById('react')
41
);
JavaScript
1
2
1
.divs { border: 1px solid #676767; padding-left: 0.3em; }
2
.divs, .counter { margin-bottom: 1em; }
JavaScript
1
3
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
2
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
3
<div id="react"></div>