Ways to program a checkbox to perform various functions depending on whether it is checked or unchecked

Hey there, I'm facing an issue with a checkbox. When it's checked, it should save a value, and when it's unchecked, it should delete that value. I tried the "easy way" in the "Controlled" section of Material UI's Checkbox documentation, but it didn't work for me. So, I looked for alternative solutions and stumbled upon a similar problem on Stack Overflow about calling 2 functions on click of a regular checkbox.

 Relevant code

const [studentID, setStudentID] = useState([])
const setStudent = (student) => {
  var checkBox = document.getElementById('checkBox');
     if(checkBox.ariaChecked == true){
         console.log("Save data")
         let data = studentID;
         data.push(student);
         setStudentID(data);
         console.log(studentID)
      } 
       else{
         console.log("Delete data")
        }  
}

                <Checkbox  
                color = "primary"
                id = "checkBox"
                onChange = {() => setStudent(student.uid)}
                inputProps={{ 'aria-label': 'controlled' }}
                />

I attempted to adapt suggestions from other posts, but they only go through one option. I haven't implemented the code to delete the value yet; I just added a console log for now.

if I invert them this is how it looks when I try to save data (this does works but since it only does one or the other it repeats)

Any tips, suggestions, documentation, or help would be greatly appreciated. Feel free to reach out if you need more information.

Answer №1

To begin with, controlling the state of a component is essential. This involves managing when it is checked and when it is not. To achieve this, you should include an attribute called "checked" in your component as part of its state:

    const [ checked, setChecked ] = useState(false)

    <Checkbox  
      checked={checked}
      ...
    />

Once this step is complete, there are two approaches you can take. The first option involves implementing the functionality as follows:

const [studentID, setStudentID] = useState([])
const [ checked, setChecked ] = useState(false)

const setStudent = (estudiante, check) => {
  console.log(estudiante, check)
  setChecked(prevState => !prevState);
     if(check){
         console.log("Save data")
         let data = studentID;
         data.push(estudiante);
         setStudentID(data);
         console.log(studentID)
      } 
       else{
         console.log("Delete data")
        }  
}

    <Checkbox  
      checked={checked}
      color = "primary"
      id = "checkBox"
      onChange = {() => setStudent(estudiante.uid, checked)}
      inputProps={{ 'aria-label': 'controlled' }}
    />

The second option utilizes the useEffect hook:

    const [studentID, setStudentID] = useState([])
    const [ checked, setChecked ] = useState(false)
    const [ id, setId ] = useState(null)
    
    useEffect(() => {
       const setStudent = () => {
        if(checked){
          //your code
        }else{
          //your code
        }
       }
       if(!isFirstTime){
          setStudent()
       }
    },[checked, id])

        <Checkbox  
          checked={checked}
          color = "primary"
          id = "checkBox"
          onChange = {() => {setId(estudiante.uid),setChecked(prevState => !prevState)}}
          inputProps={{ 'aria-label': 'controlled' }}
        />

UPDATE:

If the checkbox is within a map, you can use the data state to reflect the checked checkboxes like so:

const [studentID, setStudentID] = useState([])

// Example code for demonstration purposes
const setStudent = (estudiante) => {
  if (setStudentID.find(studentId => studentId === estudiante.uid)) {
    setStudentID([ ...data, estudiante])
    ... //your code
  }else{
    setStudentID(data.filter(studentId => studentId !== estudiante))
    ... //your code
  }
}

    <Checkbox  
      checked={setStudentID.find(studentId => studentId === estudiante.uid)}
      color = "primary"
      id = "checkBox"
      onChange = {() => setStudent(estudiante.uid)}
      inputProps={{ 'aria-label': 'controlled' }}
    />

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

Utilizing pseudo-selectors in customizing styleOverrides within MUI version 5 Theming

The documentation for MUI(v5) includes an example highlighting the use of global style overrides: const theme = createTheme({ components: { MuiButton: { styleOverrides: { root: { // How to use pseudo-class here? // I ...

React Router integration problem with Semantic UI React

Just diving into ReactJS and encountering a problem with using "Menu.Item" (from Semantic UI React) and React Router. I won't include my imports here, but rest assured they are all set up correctly. The constructor in my "App.jsx" looks like this: ...

Guide to activating the isActive status on a live link within a map iteration utilizing the NEXTUI navigation bar

Check out the new NEXTUI navbar I'm using: I am having trouble setting the isActive property on the active link in my NavBar component in Next.js. I couldn't find much help on Google, so I'm hoping someone here has experience with this or k ...

State loss occurs when moving to a different page using next/link

Currently, I am working on a library application with Next.js. Within this project, there are two main pages: BooksPage, which displays a list of all books, and BookPage, where detailed information about a specific book is shown. The components involved in ...

Material-UI Grid in Full Width Mode is malfunctioning

I've been delving into the Material-UI@next grid layout system to grasp its intricacies. What I'm aiming for is to have two papers that stretch across the entire width of the screen and collapse into one paper when the screen size shrinks. The d ...

Background Design using React-Native SVG

I'm trying to incorporate an SVG background pattern in React-Native. My approach involved creating a Component using the 'react-native-svg' library, shown below: import React from "react"; import { SvgXml } from "react-native ...

Is it possible to create a development build using Npm with React and Typescript?

I have successfully set up a TypeScript React app by using the command below: npx create-react-app my-app --template typescript However, running "npm start" generates development javascript files and launches a development server which is not id ...

Could I possibly incorporate @mui/material into an Angular project?

Is it possible to use npm install @mui/material in Angular? I am new to Angular and unsure if this will work. If not, are there any alternative Angular libraries that offer Material UI compatibility? ...

Encountering a "Module build failed: Error: ENOENT: no such file or directory" issue when attempting to import Material UI

I recently ran into an issue while developing my Next JS app. Everything was smooth sailing until I added material-ui to the project. After adding material-ui, it started throwing this error repeatedly: ./node_modules/@emotion/styled/dist/styled.browser.es ...

Steps for updating react-router-dom to version 6

Convert all Switch elements to Routes and components to element How can I update the remaining parts to v6? Routes.js import React, { lazy, Suspense } from 'react'; import { HashRouter as Routes, Route, Router } from 'react-router-dom&apo ...

Where should I store dynamically uploaded images in create-react-app?

Hey there! I've been using create-react-app and implemented a file upload feature for images. The uploads are then sent to the backend and saved locally within the project's build directory. Currently, I can reference these images dynamically via ...

A guide on utilizing the useState hook to tally occurrences of elements within an array - specifically within React's useState hook

Currently, I am tackling an exercise that involves an array containing 10 objects. Each object has properties like txt and color, for example: arr = [{txt: "txt1", color: "red"}, {txt: "txt2", color: "green"}, {txt: ...

What is the best way to create a responsive Material UI Modal?

I have set up a Modal with a Carousel inside, but I am struggling to make it responsive. Despite trying various CSS solutions from StackOverflow, nothing seems to be working for me. How can I resolve this issue? CSS: media: { width: "auto&quo ...

Synchronizing data between React Parent and Child Components is seamless even when the data is not related

Having some trouble with unrelated arrays that are somehow taking on the same value. Here is a code snippet showcasing the issue - any assistance would be greatly appreciated: https://codesandbox.io/s/aged-frost-thwsfz?file=/src/App.js The Issue: I have ...

What is the best practice for storing references to DOM elements in Reactjs?

class SearchInput extends React.Component { constructor(props) { super(props); this.searchInputRef = React.createRef(); // ...

Modifying React state within nested setTimeout callbacks

Could someone please help me understand why the 'video variable' state remains false even after the h2 element has rendered and is visible? When I click to call the hideVideo function, the video state doesn't change. Thank you for your assis ...

Creating a User Interface Table with Selectable Cells in Material Design

I am currently developing a weekly event scheduler where users can select one or more table cells to add events. However, I am encountering issues with making each cell selectable and identifying the specific cell being clicked during a click event. class ...

The functionality of CSS transitions may be affected when dynamically adding a class

Creating a custom CSS for my main div: .main { height: 0%; position: absolute; width: 100%; z-index: 100; background: whitesmoke; bottom: 0; border-radius: 15px; padding: 20px; color: gray; left: 0; right: 0; transition: height 1s e ...

The occurrence of TypeError in next.js Dropzone stating that (0 , _mantine_core__WEBPACK_IMPORTED_MODULE_0__.rem) is not a function is indicating

I am encountering an issue while trying to render a dropzone component using Next.js and Mantine. For reference, I am following the documentation at . Here is the import statement: import dropzone I am receiving an error message that says: I have inclu ...

What could be causing my carousel layout to display vertically instead of horizontally when using flex?

I currently have a carousel set up to display store products. However, I am encountering an issue where the images are rendering vertically on the screen instead of overlapping each other as they should in a carousel format. You can see the code in action ...