Home > Enterprise >  I want to disable the options for each question saperately after clicking the option for that questi
I want to disable the options for each question saperately after clicking the option for that questi

Time:01-29

        setIsStarted(true)
        setCurrentScore(0)
        setResultCard(false)
        setCurrentQuestion(0)
    }   

    const checkOption = (isCorrect) =>{
        setDisability(true)
        if(isCorrect){
            setCurrentScore(currentScore 1);
        }
        setCurrentQuestion(currentQuestion 1);

        if(currentQuestion==questions.length-1){
            setShowResult(true);
        }

    }

    function showResultButton(showResult){
        if (showResult) {
            return <button className='show-result' onClick={showResultCard}>Show results</button>
        }
    }

    const showResultCard = () =>{
        setShowResult(false)
        setResultCard(true);
        setIsStarted(false)
    }

    function displayResultCard(resultCard){
        
        if(resultCard){
            return <div className='score-card'>You have answerd {currentScore}/5 correctly</div>
        }
    }

    const updateDisability = () =>{
        setDisability(false)
    }

    function DisplayQuesion(){
        const quesList = questions.map((element) => {
            return(
                <div className='question-card'>
                    <h2>{element.text}</h2>
                    <ul>
                        {element.options.map((option) => {
                            return <button key={option.id} onClick={() => checkOption(option.isCorrect)} disabled={updateDisability}>{option.text}</button>
                        })}
                    </ul>
                </div>
            )
        })

        return (<div>{quesList}</div>)
    }

In this code my all options are getting disabled even after clicking one option.When an option for a question is clicked, all other buttons for the question are disabled. when all questions are answered, the show results button gets shown.

CodePudding user response:

This happens because you're not splitting down the list of questions in child components and so on. You need to create three components to achieve this:

  1. Questionary
  2. Question
  3. Answer

By doing so, you'll be able to define a separate state for each question/answer so they don't get mixed up.

Within your code, notice that if you click on an item it will update the state of the entire component which consequentially will update also all the other answers because they shared the same state.

You can check this link to have a better understanding: https://www.pluralsight.com/guides/passing-state-of-parent-to-child-component-as-props

  • Related