CKEditor updating React state

Viewed 577

I am using CKEditor5 with React.

Functionality: User creates multiple questions with answer options.

Simplified version of code:

function QuestionComponent() {
  const [questions, setQuestions] = useState([{ question: null, choices: [] }]);
  const [index, setIndex] = useState(0);

  function previous(e) {
    e.preventDefault();

    setIndex(index - 1);
  }

  function next(e) {
    e.preventDefault();

    // Adding new empty question
    if (questions.length <= index + 1) {
      setQuestions([...questions, { question: null, choices: [] }]);
    }

    setIndex(index + 1);
  }

  function handleQuestionInput(value) {
    setQuestions(
      questions.map((el, i) => {
        if (i === index) {
          el.question = value;
        }

        return el;
      })
    );
  }

  function handleChoiceInput(value, choiceIndex) {
    setQuestions(
      questions.map((el, i) => {
        if (i === index) {
          el.choices[choiceIndex].text = value;
        }

        return el;
      })
    );
  }

  return (
    <>
       <CKEditor
          editor={Editor}
          config={EditorConfig}
          data={questions[index].question || ""}
          onChange={(event, editor) => {
          const data = editor?.getData();
          handleQuestionInput(data);}}
        />

        <div className="choices-box">
          {questions[index].choices.map((el, i) => (
            <CKEditor
              editor={Editor}
              config={EditorConfig}
              data={el.text || ""}
              onChange={(event, editor) => {
              const data = editor?.getData();
              handleChoiceInput(data, i);
              }}
            />))
          }
        </div>

        <button
           type="submit"
           label="Previous"
           onClick={previous}
         />
          <button
           type="submit"
           label="Next"
           onClick={next}
         />
         
}

Problem: Whenever Next or Previous is clicked current question (questions[index].question) value is cleared and set to "" (or default value from data={questions[index].question || ""}) . However, choices keep their state and work well.

I tested that this code works well if I change CKEditor with simple input

I am also wondering why it is working with choices, but not question

Thanks in advance

0 Answers
Related