dimanche 20 janvier 2019

How to make dynamic checkbox and post the data using fetch post?

I have a constant file with this data in it:

export let testing= [
  { id: 'test1', label: 'Test1' },
  { id: 'test2', label: 'Test2' },
  { id: 'test3', label: 'Test3' }
]

In my checkboxes.js,

class CheckBoxes extends Component {
  constructor(props) {
    super(props);
    this.state = ({
      checkBoxArray: [],
      isChecked: false 
    })
  }

  handleSubmit = (event) => {
    event.preventDefault();     //use for testing only
   fetch(`${process.env.REACT_APP_SERVER_URL}/testing`, {
      method: "POST",
     headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        check_box_data: event.target.check_box_name[].value,   //error
      })
    })
      .then(response => {
        console.log(response);
        if (response.status === 200) {
          console.log('Success')
        } else {
          alert('Failed')
        }
      })
      .catch(error => {
        alert('Server error')
      });
  }

  handleCheckBoxChange = (index) => {     //not working
    const {checkBoxArray} = this.state;

    checkBoxArray[index].checked = !checkBoxArray[index].checked;
    this.setState({           //this line causes maximum depth mount error
      checkBoxArray
  });
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
           <div>
                {
                  this.state.checkBoxArray.map((object, index) => {
                    return (
                      <CheckBoxComponent
                        key={index}
                        check_box_id={object.id}
                        check_box_name='check_box_name[]'
                        check_box_label={object.label}
                        check_box_value={object.id}
                        isChecked={this.state.isChecked}
                        handleCheckBoxChange={this.handleCheckBoxChange(index)}
                      />
                    );
                  })
                }

            <SingleButtonComponent button_type='submit' button_value='Create Now' />
          </div>
        </form>
      </div>

    )
  }
}

export default CheckBoxes;

In my checkbox component js:

import React from 'react';

const CheckBoxComponent = (props) => {
  const { check_box_id, check_box_name, check_box_label, check_box_value, isChecked, handleCheckBoxChange } = props;
  return (
    <div>
      <input type='checkbox' id={check_box_id} name={check_box_name} value={check_box_value} checked={isChecked} onChange={handleCheckBoxChange}/>
      <label htmlFor={check_box_id} className='lh-copy'>&nbsp;{check_box_label}</label>
    </div>
  )
}
export default CheckBoxComponent;

My first problem is I can't post the checkbox value as an array in the fetch api. Apparently [] is not allowed in event.target.check_box_name[].value. I tried doing event.target.check_box_name.value but it returns cannot read property 'value' of undefined. I want to send an array of the checkbox values back to server.

My second problem is I do not know how to setup dynamically generated checkbox. This piece of code will check all the check boxes. I am showing just 3 lines of data in the constant file and it is more than that so I will not accept any solution that works statically.

Please let me know if you need me to add more details or anything. Thanks in advanced.




Aucun commentaire:

Enregistrer un commentaire