Etika49
Etika49

Reputation: 752

react.js handling multyple checkbox fields

I am working on a quiz application and would like to enable my users to go back and forth over the questions and see what they have already selected in the previous questions.

I am storing all of the data about the questions and the answers that they selected in the state. However, I am not able to render the selected checkboxes as they should be.

if I put a variable in the checked field just like the one below (checkbox) then all checkboxes within the question are affected and I only want to check just the selected ones. here is example code

https://codesandbox.io/s/confident-night-zyy2h?file=/src/App.js

import React, { useState } from "react";
import "./styles.css";

const answersArray = ["answer1", "answer2", "answer3", "answer4"];
const selectedAnswers = ["answer1", "answer3"]


export default function App() {
  const [checkbox, setCheckbox] = useState(false);

  function handleCheckbox() {}

  return (
    <div className="App">
      <h1>question 1 - how to manipulate the checkboxes</h1>

      {answersArray.map((possibleAnswer, index) => (
                        <li key={[index, possibleAnswer]}>
                            <div>
                                <input
                                    name={[index, possibleAnswer]}
                                    type="checkbox"
                                    
                                    onChange={(event) => handleCheckbox(event, index)} 
                                    checked={checkbox}
                                  />
                                
                            </div>
                            <div>
                                <span>{possibleAnswer}</span>
                            </div>
                        </li>
                    )
                    )}
    </div>
  );
}

Any ideas on how to go about this problem? I would like to render answer 1 and 3 for example as selected and make sure my users can also unselect them and change them if they wanted.

Upvotes: 0

Views: 272

Answers (2)

Mosia Thabo
Mosia Thabo

Reputation: 4277

You could do this on your input checked attribute:

checked={selectedAnswers.includes(possibleAnswer)

This will be true if the possibleAnswer is included inside selectedAnswers array.

Upvotes: 1

arnelisk
arnelisk

Reputation: 96

I am not quite sure what is the exact question, but I would like to provide you my answer. Since each checkbox has an individual state of being checked or unchecked, one state field does not solve your issue, cause using one state field for all of them defines their checked/unchecked state together. This is why you had the problem of them being checked/unchecked at the same time.

The approach to solve this would be to create individual state fields for each checkbox, but obviously that is not the smartest solution. Therefore, I would recommend you to create a separate checkbox function, which has a state field inside of it, making it individual for the checkbox itself. In my code provided below, there is an ESLint error, which would be solved if you created a separate file and moved the function there.

Additionally, if you wanted to add or remove items from the selectedAnswers array, you could do so in the onChange function. Hope, this answers your question.

import React, { useState } from "react";
import "./styles.css";

const answersArray = ["answer1", "answer2", "answer3", "answer4"];
const selectedAnswers = [];

export default function App() {
  const checkboxComponent = (index, possibleAnswer) => {
    const [checked, setChecked] = useState(false);
    return (
      <>
        <div>
          <input
            name={[index, possibleAnswer]}
            type="checkbox"
            onChange={() => setChecked(!checked)}
            checked={checked}
          />
        </div>
        <div>
          <span>{possibleAnswer}</span>
        </div>
      </>
    );
  };

  return (
    <div className="App">
      <h1>question 1 - how to manipulate the checkboxes</h1>
      {answersArray.map((possibleAnswer, index) => (
        <li key={[index, possibleAnswer]}>
          {checkboxComponent(index, possibleAnswer)}
        </li>
      ))}
    </div>
  );
}

Upvotes: 2

Related Questions