lundi 11 mars 2019

selection limit function not working on checkbox form reactjs

I have a react component that checkboxes fetched from json, each section of the checkbox can contain up to 5 checkboxes, i am trying to set the limit in each section to maximum of 2 selections, however it is not working as it should, the main component is itemlist.js, and the checkboxes come from checkbox.js, here is a live snippet of what i am trying to do, https://codesandbox.io/embed/84lo55n689?fontsize=14, the changes are made in checkbox.js, I commented out the function and it changes for demonstration, since it makes the app crash.

Checkbox.js

    import React from "react";
import "./Checkbox.css";

/* class Checkboxes extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
    currentData: [],
    limit: 2

  }}
 componentDidMount() {

  selectData(id, event){
    let isSelected = event.currentTarget.checked;
    if (isSelected) {
      if (this.state.currentData.length < this.state.limit) {
        this.setState({ currentData: [...currentData, id] })
      }
    }
    else {
      this.setState({
        currentData:
          this.state.currentData.filter((item) => id !== item)
      })
    }
  }}
 render() { */

const Checkboxes = props => {
  const id = /*this.*/ props.childId + /*this.*/ props.childp;

  return (
    <form className="form">
      <div>
        <h2>{/*this.*/ props.title}</h2>
        {/*this.*/ props.options &&
          /*this.*/ props.options.map(item => {
            return (
              <div className="inputGroup">
                <input
                  id={id + item.name}
                  name="checkbox"
                  type="checkbox"
                  //     checked={this.state.currentData.indexOf(id + item.name) >= 0}
                  //  onChange={this.selectData.bind(this, id + item.name)}
                />
                <label htmlFor={id + item.name}>{item.name} </label>
              </div>
            );
          })}
      </div>
    </form>
  );
}; //}}

export default Checkboxes;

Itemlist.js

...

  <Checkboxes
                        key={index}
                        title={item.name}
                        myKey={index}
                        options={item.children}
                        childk={item.id}
                      />
...




Aucun commentaire:

Enregistrer un commentaire