0

I have the following code which add checkboxes in my page. The question is how can I get their values? What I am currently doing is using onChange to get the values and add it to my state but not sure if that's the best way? Whats the best practice in collecting data in input, should I use onChange or ref, I am a little bit confused with ref(I am new to ReactJS)

{Object.keys(this.state.IndustryChoice).map(key => (
                    <label className="custom-control fill-checkbox">
                      <input
                        name="Industry"
                        type="checkbox"
                        value={this.state.IndustryChoice[key]}
                        className="fill-control-input"
                        onChange={this.props.onMainToggle}
                      />
                      <span className="fill-control-indicator" />
                      <span className="fill-control-description">
                        {this.state.IndustryChoice[key]}
                      </span>
                    </label>
                  ))}

Here are other parts of my code

 handleMainObjectCheckBoxToggle = event => {
    let field = event.target.name;
    let value = event.target.value;
    let MainObject = this.state.MainObject;
    // console.log("Winning Ways", MainObject[field]);
    if (customIncludes(MainObject[field].results, value)) {
      MainObject[field].results = customRemoveStringArray(
        MainObject[field].results,
        value
      );
    } else {
      MainObject[field].results = appendObjTo(
        MainObject[field].results,
        value
      );
      // console.log(MainObject[field].results);
    }
    return this.setState({ MainObject });
  };

<FormTactics

              onMainToggle={this.handleMainObjectCheckBoxToggle}
            />
Hawk
  • 514
  • 1
  • 7
  • 22
  • Did you look at "Handling Multiple Inputs" on https://reactjs.org/docs/forms.html? It sounds like roughly what you're proposing. – Joshua R. Sep 07 '18 at 21:20
  • You you want to know what best practices are regarding forms you should check https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/ – marzelin Sep 07 '18 at 21:21
  • Possible duplicate of [How do I edit multiple input controlled components in React?](https://stackoverflow.com/questions/35965275/how-do-i-edit-multiple-input-controlled-components-in-react) – marzelin Sep 07 '18 at 21:29
  • Can we see other parts of your code? How you handle the change, how you set your state, etc? – devserkan Sep 07 '18 at 21:58
  • The "handleMainObjectCheckBoxToggle " handles the changing of my state but the problem is everytime they check one choice it only get 1 value, thats why I need to iterate to my MainObject[field].results if its already exists and add it if it doesnt exists yet. Is there a easier way? – Hawk Sep 07 '18 at 22:26

2 Answers2

0

You must put checkbox values in your state as it gives your component more power to control the checkbox updates. Just use setState on onChange method and you'll see updated checkboxes


Let me know if you need more help

Sakhi Mansoor
  • 7,832
  • 5
  • 22
  • 37
  • Yup I already getting the value for individual checkbox is there a way to get all values that was checked already when checkbox was change? – Hawk Sep 07 '18 at 22:27
  • Yes. This is how you can maintain you state, you just need to read state on `onChange` It should have all values of checkboxes – Sakhi Mansoor Sep 08 '18 at 08:23
0

I can't quite understand your code but it seems you are trying to push or remove items somewhere in the state. I don't know if it suits you but I am providing a simple solution. Main differences with your code:

  • Hardcoded Industry key.
  • I'm not mutating the state directly which is a good behavior.
  • I am using the checked value for the elements.

I'm not quite sure how you implement this code in your app and if you need the checked values elsewhere. Here, we are keeping the checked values per value in the state in case you use them in the future.

class App extends React.Component {
  state = {
    IndustryChoice: {
      foo: "foo",
      bar: "bar",
      baz: "baz"
    },
    MainObject: {
      Industry: {
        results: []
      }
    },
    checkedValues: {}
  };

  handleMainObjectCheckBoxToggle = e => {
    const { value, checked } = e.target;
    const { results } = this.state.MainObject.Industry;

    if (checked) {
      const newResults = [...results, value];
      this.setState(prevState => ({
        MainObject: {
          ...prevState.MainObject,
          Industry: { ...prevState.MainObject.Industry, results: newResults }
        },
        checkedValues: { ...prevState.checkedValues, [value]: checked }
      }));
    } else {
      const newResults = results.filter(el => el !== value);
      this.setState(prevState => ({
        MainObject: {
          ...prevState.MainObject,
          Industry: { ...prevState.MainObject.Industry, results: newResults }
        },
        checkedValues: { ...prevState.checkedValues, [value]: checked }
      }));
    }
  };

  render() {
    return (
      <div>
        {Object.keys(this.state.IndustryChoice).map(key => (
          <label>
            <input
              name={key}
              type="checkbox"
              value={this.state.IndustryChoice[key]}
              className="fill-control-input"
              onChange={this.handleMainObjectCheckBoxToggle}
            />
            <span>{this.state.IndustryChoice[key]}</span>
          </label>
        ))}
        <p>results: {JSON.stringify(this.state.MainObject.Industry.results)}</p>
        <p>checked: {JSON.stringify(this.state.checkedValues)}</p>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
devserkan
  • 16,870
  • 4
  • 31
  • 47
  • Here is the my currect architecture As you can see my form is made up of multiple form section components. The reason why I am updating the App state on each change so that once the user clicks the SubmitButton ill just send the whole App State in my api. But not sure if that's the best practice – Hawk Sep 07 '18 at 23:54