Created
July 6, 2022 14:31
-
-
Save tenphi/5ea79826556295c99c43d50cd0e8de6b to your computer and use it in GitHub Desktop.
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
// You can access React utilities as props of React object. | |
// For example: `React.useRef()` | |
interface CheckboxProps { | |
value?: boolean; | |
defaultValue?: boolean; | |
onChange?: (newValue: boolean) => void; | |
} | |
function Checkbox({ value, defaultValue, onChange }: CheckboxProps) { | |
const [innerState, setInnerState] = React.useState(defaultValue || false) | |
const handleClick = React.useCallback(() => { | |
if (value !== undefined) { | |
if (onChange !== undefined) { | |
onChange(!value) | |
} | |
} else { | |
if (onChange !== undefined) { | |
onChange(!innerState) | |
} | |
setInnerState(!innerState) | |
} | |
}, [value, onChange, innerState]) | |
React.useEffect(() => { | |
if (value === undefined && defaultValue === undefined) { | |
throw "Either value or defaultValue must be specified" | |
} | |
if (value !== undefined && defaultValue !== undefined) { | |
throw "Only value or default value must be specified" | |
} | |
}, [value, defaultValue]) | |
return <input | |
type="checkbox" | |
checked={innerState || value || false} | |
className={`checkbox ${innerState || value ? 'checked' : ''}`} | |
onChange={handleClick} | |
/> | |
} | |
function App() { | |
const [state, setState] = React.useState<boolean>(false); | |
return ( | |
<div> | |
<div> | |
<Checkbox defaultValue={false}/> | |
<span>{' '} Uncontrolled checkbox default = false</span> | |
</div> | |
<div> | |
<Checkbox defaultValue={true}/> | |
<span>{' '} Uncontrolled checkbox default = true</span> | |
</div> | |
<div> | |
<Checkbox value={false}/> | |
<span>{' '} Controlled checkbox no update</span> | |
</div> | |
<div> | |
<Checkbox value={state} onChange={setState}/> | |
<span>{' '} Controlled checkbox with update</span> | |
</div> | |
</div> | |
) | |
} | |
ReactDOM.render(<App/>, document.getElementById('app')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment