logo
down
shadow

How to handle state on array of checkboxes?


How to handle state on array of checkboxes?

By : Cedric
Date : October 21 2020, 08:10 AM
may help you . You're using the container's isChecked as the state for all of your checkboxes, using a method on your container to flip that one flag that it applies to all of them (isChecked).
Instead, either:
code :
class TableToolbarComp extends React.Component {
    state = {
        items: CheckboxItems(t) // Your code seems to have a global called `t`
    };

    onChange = (value, id, event) => {       
        this.setState(({ items }) => {
          // Copy the array
          items = items.slice();
          // Find the matching item
          const item = items.find(i => i.id === id);
          if (item) {
              // Update its flag and set state
              item.checked = !item.checked;
              return { items };
          }
        });
    };

    render() {
      const { items } = this.state;
      return (
        {items.map(item => (
          <ToolbarOption key={item.id}>
            <Checkbox
              id={item.id}
              labelText={item.labelText}
              value={item.value}
              checked={item.checked}
              onChange={this.onChange}
            />
          </ToolbarOption>
        ))}

      )
    }
}


Share : facebook icon twitter icon
How To handle Recyclerview state With checkboxes?

How To handle Recyclerview state With checkboxes?


By : ivoryjurya
Date : March 29 2020, 07:55 AM
this one helps. i am working with recyclerview . my recyclerview is populated from list and it has both states of checkbox after populating .but i have some problem when i checked or unchecked in specific position and after scrolling its still on their previous position. My code is shown below. , I do not see correcly setting checked:
code :
holder.statusCheckBox.setChecked(true);
holder.statusCheckBox.setOnCheckedChangeListener(null);

//NOT_USED constant with value of status not used
if(childrenListForAttendance.get(position).getStatus()==NOT_USED){

  //code for not used checkbox
}
//is checked is constant with value of checked status
else if(childrenListForAttendance.get(position).getStatus()==IS_CHECKED) {

     holder.statusCheckBox.setChecked(true);
     //other code
}
//code for uncheck
else{

    holder.statusCheckBox.setChecked(false);
    //other code
}

holder.statusCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        childrenListForAttendance.get(position).setIsSelected(isChecked);
    }
});
How do I handle an array of checkboxes in ejs

How do I handle an array of checkboxes in ejs


By : Tommy Lee
Date : March 29 2020, 07:55 AM
will be helpful for those in need You could set the initial values on the input element itself.
For this example, I'll assume you have a value coming in to indicate whether an announcement is "enabled" or not:
code :
<td>
  <input type="checkbox" id="enabled<%= i %>" name="enabled[<%= i %>]" <%= announcement.enabled ? "checked" : null %> >
</td>
<td>
  <input type="checkbox" id="enabled<%= i %>" name="enabled[<%= i %>]" <% if (announcement.enabled) { %> "checked" <% } %> >
</td>
Handle populating state from multiple checkboxes

Handle populating state from multiple checkboxes


By : user3638171
Date : March 29 2020, 07:55 AM
it fixes the issue I may guess that happens because state update is asynchronous and by the time you attempt to apply changes with setMarkerVisibleTo() your state is different from the one you assume it is, you may try to put const visibilityChecked = [...markerVisibleTo] into handleVisibilityChange() body:
code :
const handleVisibilityChange = ({ target }) => {
    const visibilityChecked = [...markerVisibleTo]
    const { checked, value } = target
    checked ? visibilityChecked.push(value) : visibilityChecked.pop(value)
    setMarkerVisibleTo(visibilityChecked)
}
const handleVisibilityChange = ({target:{checked,value}}) => {
    const visibilityChecked = checked ? 
        [...markerVisibleTo, value] : 
        [...markerVisibleTo].filter(val => val != value)
    setMarkerVisibleTo(visibilityChecked)
}
//dependencies
const { render } = ReactDOM,
      { useState } = React

//mocking source data      
const checkItems = [...'abcd']      

//check list component
const CheckList = ({items}) => {
  const [visibleMarkers, setVisibleMarkers] = useState(checkItems),
        onVisibilityChange = ({target:{checked,value}}) => {
            const visibilityChecked = checked ? 
                [...visibleMarkers, value] : 
                [...visibleMarkers].filter(val => val != value)
            setVisibleMarkers(visibilityChecked)
        }
  return (
  <div>
      <ul>
        {
          items.map((item,key) => (
            <li {...{key}}>
              <label>
                Option {item}
                <input 
                  type="checkbox" 
                  value={item} 
                  checked={visibleMarkers.includes(item)}
                  onChange={onVisibilityChange}
                />
              </label>
            </li>
          ))
        }
      </ul>
      <span>visibleMarkers: {JSON.stringify(visibleMarkers)}</span>
  </div>
  )
}

//render
render (
  <CheckList items={checkItems} />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>
Flutter how to handle state for row of checkboxes

Flutter how to handle state for row of checkboxes


By : Mahadi Hasan Sakib
Date : March 29 2020, 07:55 AM
Does that help First: you can't update a final List _data because final means that the list is constant. Second although I prefer that u use listView because it is clearer, you can do the following:
code :
import 'package:flutter/material.dart';

class TestWidget extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return TestWidgetState();
  }

}
class TestWidgetState extends State<TestWidget>{

  List<bool> _data = [true, true, true];
  @override
  Widget build(BuildContext context) {

    return _buildCheckBoxes();
  }

  Widget _buildCheckBoxes() {
    List<Widget> list = new List();
    Widget cb;

    for (int i=0;i<_data.length;i++) {
      cb = Checkbox(
        value: _data[i],
        onChanged: (bool value) {
          setState(() {
            // need to update _data[?]
            _data[i] = value;
          });
        },
      );
      list.add(cb);
    }

    return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: list
    );
  }

}
Handle more than 200 checkboxes storing them in state

Handle more than 200 checkboxes storing them in state


By : Parth Sanandia
Date : October 01 2020, 05:00 AM
it helps some times Here is an optimized function that will toggle an item without re rendering the entire list and using a list from useState:
code :
import React, { useEffect, useState } from 'react';

const Parent = () => {
  //list is created and maintained in parent
  const [list, setList] = useState([
    { id: 1, val: true },
    { id: 2, val: true },
  ]);
  //toggle is id to indicate what item to toggle
  const [toggle, setToggle] = useState();
  useEffect(() => {
    if (toggle) {
      //setting toggle will not re render until
      //  function is finished so no infinite loop
      setToggle();
      //here we can toggle the item from the list
      setList(
        list.map(item =>
          item.id === toggle
            ? { ...item, val: !item.val }
            : item
        )
      );
    }
  }, [list, toggle]);
  //combining parent container with parent presentational
  //  for simplicity
  return (
    <div>
      {list.map(item => (
        <ItemContainer
          key={item.id}
          item={item}
          //pass setToggle as item clicked
          itemClicked={setToggle}
        />
      ))}
    </div>
  );
};
const ItemContainer = React.memo(function Item({
  item,
  itemClicked,
}) {
  //toggeling item with id 1 will not log
  //  for item with id 2
  console.log('in item render:', item.id);
  return (
    <pre onClick={() => itemClicked(item.id)}>
      {JSON.stringify(item, undefined, 2)}
    </pre>
  );
});

export default Parent;
Related Posts Related Posts :
  • jQuery target next of the same class in the whole DOM
  • encoding must be a valid encoding error in process encoding
  • How to do a date range to view data from selected date highcharts
  • How do I refactor this composed function with Ramda.js?
  • jQuery to serialize selected option's value, not label
  • Convert object to Chartis.js structure
  • Dynamic import with not bundled file
  • Click handler not firing for elements rendered in Ajax Callback - only in Safari
  • Math.max.apply gives an error CreateListFromArrayLike called on non-object
  • get the parent nodes to a given node in d3 dendogram
  • is-dropdown-submenu-parent makes links unclickable on Opera and Chrome
  • JS: Sum column values and updating result on change
  • Query against nested object keys
  • Fullcalendar getting its parent colspan
  • How to retrieve a dynamic number of elements by id
  • How to access redux variables and functions from deep components
  • Efficiently access Array.prorotype.filter single-item returns
  • PHP var into Javascript
  • How to parse json with javascript/jquery if content matches string
  • How can I make a pyramid based on alphabet?
  • Javascript sorting a csv rows and displaying in table
  • How to get specific data from json from api using ajax. The json looks strange to me
  • react js html5 video not working
  • Javascript Angular 4 Change ngClass from another Component
  • Hide multiple table columns with javascript
  • Convert datetime to ISO Format using moment js
  • Dynamically adjust canvas size depending on content
  • setTimeout function with document on click
  • Need advice on nested Promises.all
  • Google Captcha expiration time
  • Syntax of Javascript TAPE unit test
  • Parse php json to javascript
  • Write to Internet Explorer javascript console with vba in excel
  • 2 Forms with Jquery
  • Why the loop stops right in the middle?
  • filter system for restaurant booking
  • how to add active class in framework nav menu when (add/edit) pages are opened
  • Port a js map in dart
  • How to get value from select using javascript
  • Audio won't be muted with JavaScript - removing audio tags with mutationobserver needed
  • How to include an HTML/Javascript game into reactJS website
  • Convert Nodejs server into node module
  • Strage Vue behaviour. V-if does not watch properly
  • Is it possible to use map/filter/reduce inside a promise by returning the result with Promise.resolve?
  • Does EcmaScript have any rule where whitespace is important for the compiler during parsing
  • How is DOM and Virtual DOM represented in memory?
  • cannot display text onchange select option
  • My gulpfile can edit (change) and delete file, but dont copy new (add) files
  • How do I reset scroll position of paper-dialog-scrollable?
  • Loading unlooped gif-animation several times
  • Strange error from Google API: initializeAutocomplete is not a function
  • Array state variable is not being set during componentWillMount
  • Stop refresh on form submit when using javascript
  • Npm WARN deprecated babel-preset-es2015@6.24.1: Thanks for using Babel: we recommend using babel-preset-env now: please
  • Cant get wheel scroll delta on Firefox
  • Puppeteer with Prompt, ignoring rest of function
  • VueJS Form Input Binding
  • How To Extend mail.Chatter Widget in Javascript Odoo 10
  • How Chk two checkboxes at a time using jQuery
  • Broken "if" statement in JavaScript code…
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org