choose user by ticking the checkbox

For each user in the table, I aim to create a checkbox. Here is my tableBody:

<TableBody>
  {users.map((user) => {
    return (
      <TableRow key={user.id}>
        <TableCell padding="checkbox">
          <Checkbox
            checked={selectedUserIds.indexOf(user.id) !== -1} // checking if user id is in selectedUserIds
            onChange={() => handleSelectUser(user.id)} // struggling to understand the logic for this function
            value="true"
          />
        </TableCell>
        <TableCell>{user.email}</TableCell>
        <TableCell>{user.roles}</TableCell>
        <TableCell>{user.status}</TableCell>
      </TableRow>
    );
  })}
</TableBody>;

In order to store the selected ids, I have implemented this hook like in the example above:

const [selectedUserIds, setSelectedUserIds] = useState([]);

The main issue lies in finding the correct logic for the handleSelectUser function, which should add or remove the user from the selectedUserIds. I have attempted numerous times but without success.

If anyone could assist me with this, I would greatly appreciate it.

Answer №1

function selectUser(id) {
  const index = selectedIds.indexOf(id);
  let newSelectedIds = [];

  if (index === -1) {
    newSelectedIds = newSelectedIds.concat(selectedIds, id);
  } else if (index === 0) {
    newSelectedIds = newSelectedIds.concat(selectedIds.slice(1));
  } else if (index === selectedIds.length - 1) {
    newSelectedIds = newSelectedIds.concat(selectedIds.slice(0, -1));
  } else if (index > 0) {
    newSelectedIds = newSelectedIds.concat(
      selectedIds.slice(0, index),
      selectedIds.slice(index + 1)
    );
  }

  setSelectedIds(newSelectedIds);
};

Explore more about Array.prototype.concat and Array.prototype.slice

Answer №2

Here is a possible solution:

const handleSelectedUser = (id) => {
  // Check if the id is in the list of selected users
  if (selectedUsers.includes(id)) {
    // Remove the id from the selectedUsers array
    setSelectedUsers(selectedUsers.filter((userId) => userId !== id));
  } else {
    // Add the id to the selectedUsers array
    setSelectedUsers([...selectedUsers, id]);
  }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing a Customized Filtering Mechanism in Angular 8

I have some experience working in web development, but I am relatively new to Angular. My current project involves creating a simple filter for a table's column based on user input. However, I'm facing an issue where typing in a single letter fil ...

What is the best way to encapsulate all request handlers within a wrapper function in an Express application?

While working on my express application, I came across the idea of creating a wrapper function to handle async request handler functions in a more efficient way. Instead of having a try-catch block for each handler, I wanted to streamline the process by cr ...

Attempting to configure a webhook eventsub through the Twitch API by utilizing ngrok as the intermediary

After triggering a test event using the Twitch CLI, an error response was received indicating: Post "https://1562-5-182-32-19.ngrok.io/api/twitch/eventsub/": context deadline exceeded (Client.Timeout exceeded while awaiting headers). The notification even ...

Struggling with updating the header in React Navigation?

Having trouble updating the screen header in my react native application when navigating to the Dashboard Screen after login. I've tried different methods but can't seem to figure out what's wrong. After logging in, I navigate to the Dashbo ...

Is it possible to generate a TypeScript type by looping through a list of generic types?

Utilizing a third-party library called (react-navigation), I have encountered a Utility Type that allows for merging two types together. However, when attempting to merge more than two types, the process requires nesting the Utility multiple times to achie ...

How can we eliminate every item of a specific type from an array?

On my Angular controller, I've set up a method linked to a click handler in the scope. This function checks if a checkbox is checked or unchecked and toggles the associated objects in an array accordingly. The code block where I push objects back int ...

"Encountering issues with Node.js while loading required modules

Having created an API utilizing hummus.js, I encountered a problem after uploading it to my server (Ubuntu Root + Plesk Onyx) and performing an npm install on my package.json. Despite receiving a "Success" status message during the installation process, my ...

Could one potentially use jQuery to navigate through JSON output?

My goal is to generate a JSON list that includes CSS classes and their respective URL records. Here's an example: var jsonList = [{ "CSSClass": "testclass1", "VideoUrl": "/Movies/movie.flv" }, { "CSSClass": "testclass2", "VideoUrl": "/Movies/ ...

React: Issue with Rendering Custom Component Inside Double Mapping Loop

I am currently facing an issue in React as I work on a modal Form using Material-UI Field components. Each Field type such as Select, Text, and Shrink has its own Component. To handle more complex events like displaying more fields depending on a field&apo ...

A lesson is what I'm seeking, as I face an Uncaught TypeError: Unable to locate the property 'split' of an undefined value

Although this question has been asked multiple times before, I am a beginner and eager to learn. I would greatly appreciate it if someone could take the time to explain this to me. I have tried to find a solution to this error using the existing answers, b ...

Guide to sending JSON data to a server and retrieving it back using AJAX - a detailed breakdown of the

As I work on my project web page, I am exploring the use of JSON to facilitate the transfer of data between the user and the server. However, I find myself a bit puzzled about the sequence of steps involved in each JSON method. Here is my current understan ...

What is the best way to save a jQuery or JavaScript variable into a JSON file?

Is there a way to save a jquery variable in a json file? I have the following: var image='/test/test.png'; I am obtaining this path through file upload: <input type="file" name="imageurl" value="imagefile"></input> Therefore, I ne ...

Having trouble with passing props in React. Any suggestions on what I might be missing?

It seems like I am facing an issue with passing props in React, and for some reason, it's not functioning as expected. I'm a bit puzzled by the whole situation. Main Application Component import React from 'react' import Produc ...

Avoid triggering react-query to fetch data on page load, but instead set up a manual refetching mechanism

Currently, I'm utilizing react-query v3.13 for retrieving information from an API. Instead of fetching data immediately when calling useQuery, my goal is to fetch the API periodically starting from a specific point (such as clicking a start button). ...

Submitting forms with Ajax using Jquery

I'm looking to utilize ajax to submit a form in the background. My attempt so far is as follows: <div class="form-horizontal" id="form"> <label for="name" class="control-label">Enter your name</label> <div class="controls ...

Steps for Setting Up and Organizing a Fresh Event

My goal is to generate new events (using document.createEvent() or Jquery.Event) by duplicating all essential attributes, and then sending the clone to prevent alterations to the original event. For reference, the source code can be found at http://jsfid ...

"Material-UI in combination with React Hook Form fails to display error messages based on validation rules

I recently started using react-hook-form and despite doing extensive research, I am still struggling to figure out what I'm doing wrong. I created a sandbox where I have a basic input number. My ideal form behavior: I want the default value (16) to b ...

Using Vue Composition API to invoke a child component's method that employs a render function

While using Vue composition-api with Vue2, I encountered an issue when attempting to call a method of a component with a render function from its parent component. Everything works fine without the render function. TemplateComponent.vue <template> ...

Guide on changing label background color in React

Would you be able to guide me on how to change the background color of the label in react? I am utilizing react + material ui from this source. You can find information on writing CSS in js at this page. Some plugins like jss-nested are available for this ...

Switching image source using JavaScript with a button click

I am working on a code where I need to change the image source by clicking a button and also increment the counter to display the next photo. However, I am currently facing an issue where only the first photo is being displayed out of the 8 available image ...