Home > Mobile >  Reactjs shows the message in console but not in UI
Reactjs shows the message in console but not in UI

Time:01-16

I am new in Reactjs and I met an issue trying to update the DOM dynamically. In the code below the console shows the "currentQuestion.theQuestion" but it does not appear in UI.

function nextQuestionFunction () {
      let index = questions.indexOf(currentQuestion);
      index  = 1;
      //mallon thelei setState gia na doulepsei
      currentQuestion = questions[index];
      console.log(currentQuestion.theQuestion);
    }

    return ( 
      <div>
          <p>{currentQuestion.theQuestion}</p>
          <ul style={{listStyleType : 'none'}}>{answers}</ul>
          <button onClick={() => nextQuestionFunction()}>Next Question</button>
      </div>
    );

CodePudding user response:

You must store data to state to use on return function, not local variable cuz local variable only used on block scope function.

    const [currentQuestion, setCurrentQuestion] = React.useState('');

    function nextQuestionFunction () {
      let index = questions.indexOf(currentQuestion);
      index  = 1;
      currentQuestion = questions[index];
      setCurrentQuestion(currentQuestion.theQuestion);
    }

    return ( 
      <div>
          <p>{currentQuestion}</p>
          <ul style={{listStyleType : 'none'}}>{answers}</ul>
          <button onClick={() => nextQuestionFunction()}>Next Question</button>
      </div>
    );
  •  Tags:  
  • Related