So this is a form where the user can add sections to add a question (to build a quiz) and I notice that when I fill in the Answer Choices and put a file in my dropZone (drop works but doesn't update correctly, you can ignore this) the Answer Choices and dropZone rerender and the fields like refresh and become empty.
I am not entirely sure why this is happening, i have tried looking at similar issues but I couldn't get it to work. Here is my CodeSandbox with my App.
I am thinking that it may be the addQuestion function in my Questions component. Here's the code for that:
addQuestion = question => {
questionIdx++;
var newQuestion = { uniqueId: uuid(), question: "" }
this.setState(prevState => ({
questions: [...prevState.questions, newQuestion]
}));
return { questions: newQuestion }
};
I am new to React and Js so any tips/explanations will do loads of help. Thanks!
When you add a new question, and update the
Questionscomponents state variablequestions(Array type), the whole component (Questionsand its children) goes through an update process where it recalculates the output DOM tree (a virtual DOM) based on the new state and compares it to the pre-state-change virtual DOM. Before anything is 'rerendered' it checks to see if the virtual DOMs of the two versions are different among other things, if they are it will rerender the parts that change as efficiently as possible.In your case, the recalculation sees many
Answerscomponent inside of manyQuestionand sinceAnswersdoesn't have any props, it is basically a fresh render to its initial state which includes 4 empty inputs. The simplest solution I can think of is in the state of theQuestionscomponent, make sure each object in thethis.state.questionsArray has ananswersattribute (of type Array of Objects). In theaddQuestionmethod modifyvar newQuestion = { uniqueId: uuid(), question: "" };to includes this data on the answers related to that question.Then when rendering each individual question, pass this answer data (Array of answers) as a prop to
Answersand in turn to each individualAnswercomponent based on the index (an Object or a String). At the same time, you must pass anupdateAnswersmethod as a prop toQuestionthat in turn is passed toAnswersandAnswer, that is called when anAnswers input field is changed. The question id and the id of the answer needs to be passed to this method to ultimately modify the answer data that should be now stored in the state of theQuestionscomponent. I adjusted the code from the sandbox below to work along these lines, although I didn't make sure to cleanup all the damage: