dimanche 30 août 2020

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.




Aucun commentaire:

Enregistrer un commentaire