nishi
nishi

Reputation: 550

Select specific checkbox among an array of checkboxes

I have data coming from getTasks() and I store it on tasks I created a component for each task with their data with a checkbox for each task. I want to click a checkbox and display only the one I clicked, not them all. I am using React Native. How can I do this? thanks.

export default () => {
  const [tasks, setTasks] = React.useState([]);
  const [checked, setChecked] = React.useState(false);

  React.useEffect(() => {
    (async () => {
      const response = await getTasks();
      setTasks(response);
    })();
  }, []);

  return tasks.map(({id, title, description, date}) => (
    <View key={id} style={styles.task}>
      <CheckBox
        value={checked}
        onValueChange={() => {
          setChecked((prevState) => !prevState);
        }}
      />
      <View style={styles.taskTextContainer}>
        <Text>{title}</Text>
        <Text>{description}</Text>
        <Text>{date}</Text>
      </View>
    </View>
  ));
};

Upvotes: 1

Views: 119

Answers (2)

Jan C&#225;ssio
Jan C&#225;ssio

Reputation: 2279

You have two problems in that code, first is the problem you described, the second one is the way you're changing the state of that checkbox.

About the first problem, in order to display the respective state for each task, you should also include a property that defines if the task is marked or not.

First, verify the name of the property thats set if the task is done or not, I'll give the name here as done and done is of type boolean.

// notice the done property
return tasks.map(({id, title, description, date, done}) => (

Then, you should use done to change the checked state of your Checkbox like this:

<Checkbox
  value={done}
  ...
/>

Now you should change a little how you change that checked state.

First, you need to write a function to change the value of done, to fase or true, according by the Checkbox component's state and that's really simple:

const onCheckboxChange = (taskId) => {
  // first, let's find the index of the changed task
  const index = tasks.findIndex(({ id }) => id === taskId)

  // next, let's get the data by the index
  const data = tasks[index]

  // now, we can just toggle done value like this
  data.done = !data.done

  // then, let's assign updated data to its own index in tasks array
  tasks[index] = data

  // finally, we can update the tasks state using a copy of changed tasks
  setTasks([...tasks])
}

Upvotes: 0

Daniel Nakamashi
Daniel Nakamashi

Reputation: 29

You're passing the same value={checked} to all checkboxes. You can create an array of booleans to accomplish that.

Upvotes: 1

Related Questions