Created
May 4, 2021 00:02
-
-
Save ifindev/8900c1cc014456cf6d93fd8fd82281da to your computer and use it in GitHub Desktop.
Set State Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'react'; | |
function App() { | |
const [counters, setCounters] = useState([ | |
{ id: 1, value: 0 }, | |
{ id: 2, value: 0 }, | |
{ id: 3, value: 0 }, | |
{ id: 4, value: 0 }, | |
]); | |
const [count, setCount] = useState(0); | |
const handleIncrement = (counter, counters) => { | |
const index = counters.indexOf(counter); | |
counters[index].value++; | |
setCounters(counters); | |
}; | |
const handleDecrement = (counter, counters) => { | |
const index = counters.indexOf(counter); | |
counters[index].value--; | |
setCounters(counters); | |
}; | |
const increment = (count) => { | |
count = count + 1; | |
setCount(count); | |
}; | |
return ( | |
<div className="container mt-5"> | |
<div> | |
<p>You clicked {count} times</p> | |
<button onClick={() => increment(count)}>Click Me</button> | |
</div> | |
<div> | |
{counters.map((counter) => { | |
return ( | |
<div | |
className="d-flex flex-row align-items-center mt-2" | |
key={counter.id} | |
> | |
<span | |
style={{ fontSize: 24 }} | |
className="badge m-2 badge-primary" | |
> | |
{counter.value} | |
</span> | |
<button | |
style={{ height: 38 }} | |
className="btn btn-secondary mr-2" | |
onClick={() => handleIncrement(counter, counters)} | |
> | |
<strong>+</strong> | |
</button> | |
<button | |
style={{ height: 38 }} | |
className="btn btn-warning mr-2" | |
onClick={() => handleDecrement(counter, counters)} | |
> | |
<strong>-</strong> | |
</button> | |
</div> | |
); | |
})} | |
</div> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sepertinya gini jadi lebih ringkas
yang ini juga