Skip to content Skip to sidebar Skip to footer

Checkboxes - Getting Starting Value From State

I have the following form, and the part that works is it sets the state for each option to 'true' of 'false' as I check and uncheck the boxes as expected. My problem is that when I

Solution 1:

To pass all checkboxes value from state at once, you can grab them in a sub level of state like:

state = { checkboxes : {
  formRewardsService: false,
  formRewardsRetirement : true,
  ...
}}

and then pass only checkboxes states to Culture props

<Culture handleCheck={this.handleCheck} {...this.state.checkboxes } />

And rewrite your handleCheck function like this:

handleCheck = (e) => {
    const name = e.target.name;
    const checked = e.target.checked
    this.setState(
      {
        ...this.state,
        checkboxes: {
          ...this.state.checkboxes,
          [name]: checked 
        }
      }
    ));
    console.log(e.target.name + ': ' + e.target.checked);
  }

Solution 2:

You can remove the bind function if you write function like this:

 handleCheck = (e) => { ...

Then write this function to set the state properly like this:

handleCheck = (e) => {
    const name = e.target.name;
    const checked = e.target.checked
    this.setState(
      {
        [name]: checked 
      }
    ));
    console.log(e.target.name + ': ' + e.target.checked);
  }

Then you have to pass checked states to Culture props.

render() {
        return (
          <ThemeProvider theme={theme}>
            <Container>
              <Div>
                <Tabs defaultActiveKey="general" id="audit=tabs">
                  <Tab eventKey="culture" title="Culture">
                    <Culture handleCheck={this.handleCheck} formRewardsService={this.state.formRewardsService} ... />
                  </Tab>
                </Tabs>
              </Div>
            </Container>
          </ThemeProvider>
        );
    }

and for checkboxes:

<Form.Check
     type="checkbox"
     label="Service Awards"
     name="formRewardsService"
     id="formRewards1-1"
     checked={this.props.formRewardsService}
 />

Post a Comment for "Checkboxes - Getting Starting Value From State"