Skip to main content
4 of 4
edited tags
200_success
  • 144.2k
  • 22
  • 188
  • 473

Simple checkboxes with React

I was given the following exercise as part of a job interview process. I submitted my code and received the feedback that my solution is "close" but not "correct". My code executes just fine and displays the desired results. Can somebody please tell me what would have made my code more "correct"? or - did I misunderstand the requirements? (I realize that the Constructor is no longer needed but Codepen was complaining without it).

###Requirements:

Using data variable implement a small Form using checkboxes

[x] Sonia
[ ] Maria
[ ] John
[x] Michael

On every form change on any checkbox print its current state, which should look like data.

const data = {
  sonia: true,
  maria: false,
  john: false,
  michael: true
};

###My solution:

class App extends React.Component{

    constructor() {
        super();

        this.state = {
            data: {
                Sonia: false,
                Maria: false,
                John: false,
                Michael: false
            }
        };

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(event) {

        let data = this.state.data;

        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        data = this.state.data;

        for (const i in data) {
            if (i === name) {
                data[i] = value
            }
        }
        this.setState( {data:data});
    }

    render() {
        return (
            <div>
                <form>
                  {Object.keys(this.state.data).map((key, index) =>
                        <div key={index}>
                            <input
                                name={key}
                                id={index}
                                type="checkbox"
                                checked={this.state.data[key].value}
                                onChange={(event) => this.handleClick(event)} />

                            <span className="padding">
                                <label htmlFor={index} key={index}>
                                    {key}
                                </label>
                            </span>
                        </div>
                    )}
                </form>
                <div className="center">
                    <h2>Current State: </h2>
                    <ul>
                        {Object.keys(this.state.data).map((key, index) =>
                            <li key={index}>{ `${key}:  ${this.state.data[key]}`}</li>
                        )}
                    </ul>
                </div>
            </div>
        );
    }
}
ReactDOM.render(<App />, document.getElementById('app'));
Daisy
  • 83
  • 1
  • 4