From 4ccd760bfa818a7c2712122d59781c51e03bc696 Mon Sep 17 00:00:00 2001 From: rishichawda Date: Sun, 24 Feb 2019 14:08:40 +0530 Subject: [PATCH] fix(mutliselectcheckbox): rewrite with hooks --- snippets/MultiselectCheckbox.md | 89 +++++++++++++++------------------ 1 file changed, 40 insertions(+), 49 deletions(-) diff --git a/snippets/MultiselectCheckbox.md b/snippets/MultiselectCheckbox.md index 86827fb86..9cf92ac7f 100644 --- a/snippets/MultiselectCheckbox.md +++ b/snippets/MultiselectCheckbox.md @@ -2,63 +2,51 @@ ## -Renders a checkbox list with the options provided through `props`. +Renders a checkbox list with the `options` provided through `props`. Initially, all the items in the `options` array only have label ( and / or other data provided by the user ) and `checked` is `undefined` if not provided. On clicking any of the items, the `checked` value for the item is toggled and state is updated with the new list. -The checkbox input in this case is kept as `readOnly` since click events are handled for the item ( label + input ) and not the `input` alone. An `onChange` prop can be passed to the `MultiCheckbox` component to get the updated list on every change event within the list. +An `onChange` prop can be passed to the `MultiCheckbox` component to get the updated list on every change event within the list. ```jsx -export default class MultiCheckbox extends React.Component { - constructor(props) { - super(props); - this.style = { - listContainer: { - listStyle: "none", - paddingLeft: 0 - }, - itemStyle: { - cursor: "pointer", - padding: 5 - } - }; - this.state = { - options: props.options - }; - } +import React, { useState } from 'react' - toggle = item => { - const { options } = this.state; - const { onChange } = this.props; - options.map((_, key) => { - if (options[key].label === item.label) { - options[key].checked = !item.checked; - } - }); - this.setState( - { - options - }, - () => { - onChange(options); - } - ); - }; - - render() { - const { options } = this.state; - return ( - - ); +const style = { + listContainer: { + listStyle: 'none', + paddingLeft: 0, + }, + itemStyle: { + cursor: 'pointer', + padding: 5, } } + +const MultiCheckbox = ({ options, onChange }) => { + const [data, updateOptions] = useState(options); + + function toggle(item) { + data.map((_, key) => { + if (data[key].label === item.label) { + data[key].checked = !item.checked; + } + }); + updateOptions(data); + onChange(data); + } + + return ( + + ) +} + +export default MultiCheckbox; ``` ```jsx @@ -74,3 +62,6 @@ ReactDOM.render( document.getElementById("root") ); ``` + +#### Notes: +* The checkbox input in this case is kept as `readOnly` since click events are handled for the item ( label + input ) and not the `input` alone. \ No newline at end of file