vendredi 24 septembre 2021

How to check Dynamic Checkbox in React JS

I have a dynamic form with the following implementation. The problem is that I want to "check" the checkbox IF the answer of that "questionID" exists in the answers array with the selected option (i.e A,B). so the condition of the check should be answers[index].userChoice.option is equal to Object.keys(x). enter image description here

import fieldsL from "./fields.json"; 

function App() { 
  let [Fields , setFields] = useState([]);
  let [answers, setAnswers] = useState([]);
const updateAnswer = ((qid,option,optionValue) => {
      let ans = answers;
      let singleAns = {
        questionId : qid,
        userChoice: 
        { 
          option: option, 
          optionValue: optionValue, 
          isChecked: true
        }
      };
      if(answers.length > Fields) return console.warn("Invalid Question ID")
      if(answers.find((sp) => sp.questionId === qid)) {
        var index = answers.map(function(x1) {return x1.questionId}).indexOf(qid);
        answers[index].userChoice.option = option;
        answers[index].userChoice.optionValue = optionValue;
        console.log("Existing Answer Updated");
      }
      else ans.push(singleAns)
      ans.sort((a, b) => parseFloat(a.questionId) - parseFloat(b.questionId)); 
      setAnswers(ans)
      console.log(answers)
  })

useEffect(()=>{
  console.log("useEffect")
  setFields(fieldsL.data)
},[])
let Questions = fieldsL.data.question;
let displayFields = Questions.map((e,index)=>{
return <div key={index} >
<label className="label">{e.content}</label>

<div className="control">
{
e.radio?  e.option.map((x,index2) => {

  console.log(index)
  //console.log(x)
 return <div classID="field" key={index2}>
<div classID="control">
  <label classID="checkbox">
    <label> {Object.keys(x)[0]}     </label>

    <input type="checkbox" name="question" onChange={()=> updateAnswer(e.questionId,Object.keys(x)[0],Object.values(x)[0])}/>
    &nbsp; {Object.values(x)[0]}
    { 

    }
  </label>
</div>
</div> }
) : <span>Empty</span>
}
</div>
</div>;
})




Aucun commentaire:

Enregistrer un commentaire