custom checkbox false or true after click

Viewed 614

I'm developing a Checkbox component, because the native one doesn't work because of Expo, so I decided to create a custom one, but I'm new to react native and I'm not able to change the state of my component after the click, what I need is that after the click, the box is unchecked, and if I click again, the box is checked again, but this only happens when the checked property is true. How do I change from true to false after the click?

Index.tsx

export interface Properties {
  newColor?: Boolean;
  id?: String;
  checked?: Boolean;
  onChange?: () => void;
  label?: String;
}

const Checkbox: React.FC<Properties> = (props: Properties) => {
  const config: Config = {
    types: [
      {
        title: "",
        isDefault: true,
      },
      "",
    ],
    modifiers: ["inverse"],
    states: ["disable"],
  };
  
  return (
    <>
      <View>
        <TouchableOpacity
          {...props}
          onPress={() => handleClick()}
          style={styles.container}
        >
          <View
            style={styles.checkboxUnchecked}
          >
            {props.checked === true ? (
              <View
                style={styles.checkboxChecked}
              >
                <Icon
                  name={"check"}
                />
              </View>
            ) : (
              <View
                style={styles.checkboxUnchecked}
              >
              </View>
            )}
          </View>
          {
            <Text>
              {props.label}
            </Text>
          }
        </TouchableOpacity>
      </View>
    </>
  );
};

To use the component I call it this

<Checkbox checked={false} label={"Label"} id={"i3"}/>

but the result i have is:

enter image description here

but if I call the component this way I get another result

<Checkbox checked={true} label={"Label"} id={"i3"}/>

enter image description here

1 Answers

Use react state

Your code should be like this.

const Checkbox: React.FC<Properties> = (props: Properties) => {

    const [value, setValue] = React.useState(props.checked /*default value*/);


    const handleClick = () => {
        const newValue = !value; //switch value
        setValue(newValue);
        if(props.onChange) props.onChange(newValue);
    }


    return(

        <TouchableOpacity onPress={() => handleClick()}>

            {value === true  && <View style={styles.checkboxChecked}></View>}
            {value === false && <View style={styles.checkboxUnchecked}></View>}
        
         </TouchableOpacity>
    )
}

use it like this

<Checkbox
    checked={true} //defaultvalue
    onChange={value => alert("new value is: " + value)} //handle new value
/>
Related