lundi 19 juillet 2021

How to reset checkboxes each time component renders in ReactJS

I have a reactJS component below where I'm rendering 3 buttons. Each button, when clicked, updates this.state.networks with a new list of networks. Each time the reactJS component is rendered, a checkbox is made for each network in this.state.networks. However I notice that if I uncheck one checkbox and then hit any button again to change this.state.networks that checkbox is still unchecked however it may now be unchecked for a different network.

What I'd like to do is have ALL of the checkboxes checked each time a button is clicked. That way if you uncheck a checkbox but then hit a button to update this.state.networks and hence the checkboxes, all of the checkboxes are 'reset' or checked.

To see this in action go to my notebook: https://observablehq.com/@reneelempert/react-example

class Mychart extends React.Component {

constructor(props) {
  
  super(props);
  this.state = {
    networks: ['BET', 'BHER', 'CMDY', 'CMT', 'DISJR', 'DSNY', 'LOGO', 'MTV', 'MTV2', 'NAN', 'NICK', 'NKJR', 'NKTNS', 'PAR', 'TNNK', 'TOON', 'TVL', 'VH1'],
    customBtnSelected: 'all'
  };
  this.removedNets = [];
  this.buttons = [
    {update: ['BET', 'BHER', 'CMDY', 'CMT', 'DISJR', 'DSNY', 'LOGO', 'MTV', 'MTV2', 'NAN', 'NICK', 'NKJR', 'NKTNS', 'PAR', 'TNNK', 'TOON', 'TVL', 'VH1'], label: 'Show All', key: 'all'}, 
    {update: ['DISJR', 'DSNY', 'NICK', 'NKJR', 'NKTNS', 'TNNK', 'TOON'], label: 'Show Kids Nets Only', key: 'kids'},
    {update: ['BET', 'BHER', 'CMDY', 'CMT', 'LOGO', 'MTV', 'MTV2', 'NAN', 'NICK', 'NKJR', 'NKTNS', 'PAR', 'TNNK', 'TVL', 'VH1'], label: 'Show Legacy Viacom Only', key: 'legacy'}
  ];
  
}

createElements() {
  
  const buttons = this.buttons.map((button) => {
    return React.createElement( 'button', { className: button.key === this.state.customBtnSelected ? 'custom-btn selected' : 'custom-btn unselected', onClick: () => {this.setState({customBtnSelected: button.key, title: button.title, networks: button.update}) } }, button.label)
  });
  
  const mydiv = React.createElement('div', {}, null);
  
  const checkBoxes = this.state.networks.map((brand) => {
     return React.createElement('div', {class: 'brand-check', id: brand, style: {display: 'inline', paddingLeft: 5, paddingRight: 5}}, [React.createElement('input', {type: 'checkbox', name: brand, defaultChecked: 'checked', onClick: () => {console.log('clicked');} }, null), React.createElement('label', {for: brand, style: {fontSize: 13}}, brand)] )}
  );
  
  const myElements = buttons.concat(mydiv, checkBoxes);
  
  return myElements;

}

render() {
  const myElements = this.createElements();
  return (myElements);
}

}

// Instantiate the react component and render it
let parent = html`<div>`;
ReactDOM.render(React.createElement(Mychart), parent);



Aucun commentaire:

Enregistrer un commentaire