vendredi 1 octobre 2021

(React) Storing a checkbox value to an array in context

I have a multiple step form that I am creating and in one of the steps I need to have multiple checkboxes so that I can select one or more of them and store their value.

Now, since there are multiple steps and I need to display all of the selected answers at the end, I decided to create a context and in there use the useState hook with an empty array as the initial state where I would store the values.

import {createContext, useState } from 'react'

export const AnswersContext = createContext();

export const AnswersContextProvider = ({children}) => {

    const [selected, setSelected] = useState([])

 const AnsersContextValue = {
        selected,
        setSelected,
    }

return(
        <AnswersContext.Provider value={AnsersContextValue}>
        {children}
        </AnswersContext.Provider>
    )
 

In the modal window component, I map through the questionList where I have questions and given answers

questionList[displayQuestion].answers.map((answer) => {
      return <Answer key={uuidv4()} answer={answer} />;
const questionList = [
    {
      text: "Question"
      answers: [
        { id: 1, answer: "Answer A", points: 10 },
        { id: 2, answer: "Answer B", points: 20 },
        { id: 3, answer: "Answer C", points: 30 },
        { id: 4, answer: "Answer D", points: 40 },
      ],
    }

  export default questionList

And my answer component looks like this

import React, {useState, useContext} from 'react'
import { AnswersContext } from '../context/AnswersContext'


export default function Answer({answer}) {

    const [isChecked, setIsChecked] = useState(false)
    const { selected, setSelected } = useContext(AnswersContext)
  
    const handleSelect = (answer) => {
      let selectedCopy = [...selected]
      const found = selectedCopy.find(x=> x.id === answer.id)
      if(!found && !isChecked){
        selectedCopy.push(answer)
      }
      setSelected(selectedCopy)
      if(found && isChecked){
        setSelected(selected.filter(y => y.id !== found.id))
      }
    }
  
    console.log(selected)
    return (
        <div className="pair">
            <input
              type="checkbox"
              checked={isChecked}
              value={answer.answer}
              onChange={(e)=> {
                setIsChecked(e.target.checked)
                handleSelect(answer)
              }}
            />
            {answer.answer} ({answer.points} points)
          </div> 
    )
}

but I can't figure out how to make my handleSelect function store checkbox value in my array in context and I should somehow add up the points from each answer.

Any help would be greatly appreciated!




Aucun commentaire:

Enregistrer un commentaire