0

import React, {useState} from 'react'
import Result from './Result'
import './Exam.css'

function Exam() {

  const data = JSON.parse(localStorage.getItem('Que'))
  const selectedAns = JSON.parse(localStorage.getItem('Ans'))

  const [current, setCurrent] = useState(0)
  const [ans, setAns] = useState({selectedAns:""})
  const [correct, setCorrect] = useState(0)
  const [exit, setExit] = useState(false)

  const input = (e) => {
    //setAns((ans) => ans, e.target.value)
    setAns({...ans,
      [e.target.name]: e.target.value})
  }

  console.log(ans);

  const handlePrevious = (e) => {
    setCurrent(current - 1)

      let allRadio = document.querySelectorAll('.radioButton')

      console.log(selectedAns[(current)].selectedAns);

      allRadio.forEach(value => {
        if(selectedAns[current].selectedAns === value.value){
          value.checked = true
        }
      })


  }

  const handlerSave = () => {
    if (data[current].answer === ans) {
      setCorrect(correct + 1)
    }

    if ((current + 1) === data.length){
      setExit(true)
    }
    else {
    setCurrent(current + 1)
    }

    let allRadio = document.querySelectorAll('.radioButton')
    allRadio.forEach(value => value.checked = false)

    const answers = JSON.parse(localStorage.getItem("Ans") || "[]")
    answers.push(ans)
    localStorage.setItem('Ans', JSON.stringify(answers))

  }

  return(
    <div>
      { exit === false ?
      <div className='mcq'>
      <div>
        Question :<span className='span'>{current + 1}</span>    
        {data[current].question}?
      </div><br/>
      <div>
        <div className='option'><input type='radio' value='A' name='selectedAns' onChange={input} className='radioButton'/> {data[current].A} </div>
        <div className='option'><input type='radio' value='B' name='selectedAns' onChange={input} className='radioButton'/> {data[current].B} </div>
        <div className='option'><input type='radio' value='C' name='selectedAns' onChange={input} className='radioButton'/> {data[current].C} </div>
        <div className='option'><input type='radio' value='D' name='selectedAns' onChange={input} className='radioButton'/> {data[current].D} </div>
      </div><br/>
      <div>
        { current !== 0 && <button onClick={handlePrevious}>Previous</button>}
        <button onClick={handlerSave}>Save & Next</button>
      </div>
      </div> :
      <Result props={{correct}}/>
      }
    </div>
  )
}

export default Exam;

I am making a quiz app in react js. I am facing an issue which is that I have hundreds of questions with four options, and also next and previous buttons in that. For options, I am using radio buttons. I want that after the user selects an option for the first question, goes to the next question and selects an option for the second question, he will be able to go to the previous question, and there the radio button will be checked with the option the user has been selected earlier.

i have tried this function. but it gives me diffrent button checked const handlePrevious = (e) => { setCurrent(current - 1) let allRadio = document.querySelectorAll('.radioButton') console.log(ans); allRadio.forEach(value => { if(ans === value.value){ value.checked = true } }) }

1
  • Generally you want your inputs to be controlled by react. So the checked value is coming from state. I would first work on refactoring your code so that you can avoid using document.querySelector and rather just change the state of inputs. Alternatively you could use refs. Commented Jan 4, 2023 at 6:16

2 Answers 2

0

You can create a hook with the help of useState and add default type as object. At question -1 index you can store your value. OnSelectRadio function will accept event and index which will be called when you click on any of the radio button.

const[ans, setAns] = useState({}):


onSelectRadio(event, idx){
  let temp = [..ans];
  temp[idx+1] = event.target.value;
  setAns(temp);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks but can you elaborate your answer after checking my whole code, which i have added now.
0

I have made another function to check status of my radio button... if have any other query please check my full code first and then my solution.

const handlePrevious = (e) => {
    setCurrent(current - 1)
    Previous()
  }


  const Previous = () => {
    let allRadio = document.querySelectorAll('.radioButton')
    allRadio.forEach(value => {
      if(selectedAns[current-1].index === value.value){
        value.checked = true
      }
    })
  }
  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.