Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

refactor: Make checkbox component using React hooks (#784)

Anass-Daoudi456f273c547b
diff --git a/public/components/common/form/Checkbox.tsx b/public/components/common/form/Checkbox.tsx
index 5c82779e5..ccc326b18 100644
--- a/public/components/common/form/Checkbox.tsx
+++ b/public/components/common/form/Checkbox.tsx
@@ -1,4 +1,4 @@
-import React from "react";
+import React, { useState } from "react";
import { classSet } from "@fider/services";
import { DisplayError, ValidationContext, hasError } from "../";
@@ -8,49 +8,32 @@ interface CheckboxProps {
onChange: (checked: boolean) => void;
}
-interface CheckboxState {
- checked: boolean;
-}
+export const Checkbox: React.FC<CheckboxProps> = props => {
+ const [checked, setChecked] = useState<boolean>(props.checked || false);
-export class Checkbox extends React.Component<CheckboxProps, CheckboxState> {
- constructor(props: CheckboxProps) {
- super(props);
- this.state = {
- checked: props.checked || false
- };
- }
+ const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const isChecked: boolean = e.currentTarget.checked;
- private onChange = (e: React.FormEvent<HTMLInputElement>) => {
- this.setState({ checked: e.currentTarget.checked }, () => {
- if (this.props.onChange) {
- this.props.onChange(this.state.checked);
- }
- });
+ setChecked(isChecked);
+ props.onChange(isChecked);
};
- public render() {
- return (
- <ValidationContext.Consumer>
- {ctx => (
- <div
- className={classSet({
- "c-form-field m-checkbox": true,
- "m-error": hasError(this.props.field, ctx.error)
- })}
- >
- <label htmlFor={`input-${this.props.field}`}>
- <input
- id={`input-${this.props.field}`}
- type="checkbox"
- defaultChecked={this.props.checked}
- onChange={this.onChange}
- />
- {this.props.children}
- </label>
- <DisplayError fields={[this.props.field]} error={ctx.error} />
- </div>
- )}
- </ValidationContext.Consumer>
- );
- }
-}
+ return (
+ <ValidationContext.Consumer>
+ {ctx => (
+ <div
+ className={classSet({
+ "c-form-field m-checkbox": true,
+ "m-error": hasError(props.field, ctx.error)
+ })}
+ >
+ <label htmlFor={`input-${props.field}`}>
+ <input id={`input-${props.field}`} type="checkbox" checked={checked} onChange={onChange} />
+ {props.children}
+ </label>
+ <DisplayError fields={[props.field]} error={ctx.error} />
+ </div>
+ )}
+ </ValidationContext.Consumer>
+ );
+};