Home > Back-end >  How to use React Native Paper Checkbox or Checkbox.Item using FlatList?
How to use React Native Paper Checkbox or Checkbox.Item using FlatList?

Time:10-13

You can only check and uncheck at once with the current source. I want to do it one by one...

The number of lines in the obdngList list is not determined. As an example, I wrote two lines.

Help :( thank you!!

      const [checked, setChecked] = React.useState(false);

      const obdngList = 
      [ 
        {"a": "test1", "b": "test2", "c": "test3"}
      , {"a": "test111", "b": "test222", "c": "test333"}
      ];


                      <FlatList
                        data={obdngList}
                        renderItem={({ item }) => (
                          <Checkbox.Item 
                            label={item.a}
                            value={item.b}
                            status={checked ? 'checked' : 'unchecked'} 
                            onPress={() => {
                              setChecked(!checked)
                            }}
                          />
                        )}
                      />

CodePudding user response:

The problem with your code is you are using checked for all your checklists, meaning that if one of your checklists is "checked" then all of them will be "checked" as well.

If you want to solve your problem, you need to change the state into

const [obdngList, setObdngList] = useState([ 
    {"a": "test1", "b": "test2", "c": "test3", checked: false},
    {"a": "test111", "b": "test222", "c": "test333", checked: false}
    ]);

with this, each of the checklists has its own checked value.

Here's a solution you can try:

const [obdngList, setObdngList] = useState([
    { a: 'test1', b: 'test2', c: 'test3', checked: false },
    { a: 'test111', b: 'test222', c: 'test333', checked: false },
  ]);

  <FlatList
    data={obdngList}
    renderItem={({ item, index }) => (
      <Checkbox.Item
        label={item.a}
        value={item.b}
        status={item.checked ? 'checked' : 'unchecked'}
        onPress={() => {
          const tempArr = [...obdngList];
          tempArr.splice(index, 1, { ...item, checked: !item.checked });
          setObdngList(tempArr);
        }}
      />
    )}
  />;
  • Related