Home > database >  React toggle checkbox not toggling
React toggle checkbox not toggling

Time:11-07

I am trying to wrap content in my React app to use a different top-level element.

In my state I have defined wrapContent: false

I have defined a toggleWrap method.

toggleWrap = () =>  {
this.setState(state => state.wrapContent = !state.wrapContent);
}

And finally in my input checkbox I have included the toggleWrap method in

onChange={this.toggleWrap}

Unfortunately when I run my code, pressing on the checkbox does not wrap my component content in the following code inside my wrapContent method

wrapContent(content){
return this.state.wrapContent
? <div className="bg-secondary p-2">
<div className="bg-light"> {content} </div>

which wraps the contents of my render(){} return in this component.

What is strange is that when I manually change wrapContent: false in my state to True, I see that the checkbox is checked in my browser and that the code within my render is properly wrapped. So it seems that just my toggleWrap function is not working as it should.

Could someone help here?

Full code:

import React, { Component } from 'react'
import { ValidationDisplay } from './ValidationDisplay';
import { GetValidationMessages } from './ValidationMessages';

export class Editor extends Component {

  constructor(props) {
    super(props);
    this.formElements = {
      name: { label: "Name", name: "name", validation: { required: true, minLength: 3 } },
      category: { label: "Category", name: "category", validation: { required: true, minLength: 5 } },
      price: { label: "Price", name: "price", validation: { type: "number", required: true, min: 5 } }
    }
    this.state = {
      errors: {},
      wrapContent: false
    }
  }
  // 06.11.21- method is invoked when the content is rendered
  setElement = (element) => {
    if (element !== null) {
      this.formElements[element.name].element = element;
    }
  }

  // handleChange = (event) => {
  //   event.persist()
  //   this.setState(state => state[event.target.name] = event.target.value);
  // }

  handleAdd = () => {
    if (this.validateFormElements()) {
      let data = {};
      Object.values(this.formElements)
        .forEach(v => {
          data[v.element.name] = v.element.value;
          v.element.value = "";
        });
      this.props.callback(data);
      this.formElements.name.element.focus();
    }
  }

  validateFormElement = (name) => {
    let errors = GetValidationMessages(this.formElements[name].element);
    this.setState(state => state.errors[name] = errors);
    return errors.length === 0;
  }

  validateFormElements = () => {
    let valid = true;
    Object.keys(this.formElements).forEach(name => {
      if (!this.validateFormElement(name)) {
        valid = false;
      }
    })
    return valid;
  }
    
      toggleWrap = () => {
this.setState(state => state.wrapContent = !state.wrapContent);

      }
    
  wrapContent(content) {
    return this.state.wrapContent
      ? <div className="bg-secondary p-2">
        <div className="bg-light"> {content} </div>
      </div>
      : content;
  }

  render() {
    return this.wrapContent(
      <React.Fragment>
        <div className="form-group text-center p-2">
          <div className="form-check">
            <input className="form-check-input"
              type="checkbox"
              checked={this.state.wrapContent}
              onChange={this.toggleWrap} />
            <label className="form-check-label">Wrap Content</label>
          </div>
        </div>
        {
          Object.values(this.formElements).map(elem =>
            <div className="form-group p-2" key={elem.name}>
              <label>{elem.label}</label>
              <input className="form-control"
                name={elem.name}
                autoFocus={elem.name === "name"}
                ref={this.setElement}
                onChange={() => this.validateFormElement(elem.name)}
                {...elem.validation} />
              <ValidationDisplay
                errors={this.state.errors[elem.name]} />
            </div>)
        }
        <div className="text-center">
          <button className="btn btn-primary" onClick={this.handleAdd}>
            Add
          </button>
        </div>
      </React.Fragment>)
  }
}

CodePudding user response:

This was an issue with how you update the state

Try below

  toggleWrap = () => {
    this.setState({ wrapContent: !this.state.wrapContent });
  };

or

  toggleWrap = () => {
    this.setState((state) => {
      return { ...state, wrapContent: !this.state.wrapContent };
    });
  };

instead of

toggleWrap = () => {
   this.setState(state => state.wrapContent = !state.wrapContent);
}
  • Related