Created
September 5, 2019 06:46
-
-
Save wicksome/100784cee0e39992baeaeb7f3a5789d0 to your computer and use it in GitHub Desktop.
React Hooks Example for multiple checkbox and all checking button. https://jsfiddle.net/yeongjun_kim/1wytdenz/
This file contains hidden or 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 React, { useState } from "react" | |
const Item = { KEY1: 0, KEY2: 1 } | |
const App = props => { | |
const [items, setItems]=React.useState({ | |
all: false, | |
checked: new Set(), | |
}); | |
const handleAllCheckboxChange = e => { | |
const check = e.target.checked | |
setItems({ | |
all: check, | |
checked: new Set(check ? [Item.KEY1, Item.KEY2] : []) | |
}) | |
} | |
const handleCheckboxChange = e => { | |
const checked = new Set(items.checked) | |
const { item } = e.target.dataset | |
console.log(item) | |
if (e.target.checked) { | |
checked.add(+item) | |
} else { | |
checked.delete(+item) | |
} | |
setItems({ | |
all: checked.size === Object.keys(Item).length, | |
checked: new Set(checked) | |
}) | |
} | |
return ( | |
<div> | |
<input | |
type="checkbox" | |
id="all" | |
onChange={handleAllCheckboxChange} | |
checked={items.all} | |
/> | |
<label htmlFor="all">all</label> | |
<br/> | |
<input | |
type="checkbox" | |
id="checkbox1" | |
data-item={Item.KEY1} | |
checked={items.checked.has(Item.KEY1)} | |
onChange={handleCheckboxChange} | |
/> | |
<label htmlFor="checkbox1">checkbox1</label> | |
<input | |
type="checkbox" | |
id="checkbox2" | |
data-item={Item.KEY2} | |
checked={items.checked.has(Item.KEY2)} | |
onChange={handleCheckboxChange} | |
/> | |
<label htmlFor="checkbox2">checkbox2</label> | |
</div> | |
); | |
}; | |
ReactDOM.render( | |
<App />, | |
document.getElementById('app') | |
); |
This file contains hidden or 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
<script src="https://unpkg.com/[email protected]/dist/global-input-react.js"></script> | |
<div id="app"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment