How to make input values stay with their component when it’s filtered out from map?

  Kiến thức lập trình

I am working on creating a quiz app where the quiz creator can add multiple questions simultaneously. In my QuestionsDraft.js, there is a draft state that stores a unique ID for the selected question type (in this case, we are using multiple choice questions). Within MultipleChoiceDraft.js, the choices state is also mapped, and their values are assigned to the respective inputs.

However, when I invoke the remove function from QuestionsDraft.js to filter out a specific draft by clicking on the remove button, the text typed into the inputs remains at their previous position on the page. How can I fix this? See images for clarity.

Image 1: Added three multiple choice forms. The second one has a text.

Image 2: Removed the form with the text, which was the second form. The text remains at the same position even though the initial form where it belongs to is removed.

QuestionsDraft.js

const QuestionsDraft = () => {
    const [drafts, setDrafts] = useState([
        { id: 0, content: <MultipleChoiceDraft /> },
        { id: 1, content: <MultipleChoiceDraft /> }
    ])

    const remove = (index) => {
        setDrafts(p => 
            p.filter(draft => draft.id !== index)
        )
    }

    return (
        <section>
            {/* Other Codes */}
            <ul className="flex flex-col gap-8">
                {drafts.map((draft, index) => (
                    <li key={index}>
                        {draft.content}
                        <button onClick={() => remove(index)}>Remove Question</button>
                    </li>
                ))}
            </ul>
        </section>
    )
}

MultipleChoiceDraft.js

const MultipleChoiceDraft = () => {
    const [question, setQuestion] = useState("")
    const [answer, setAnswer] = useState(null)
    const [choices, setChoices] = useState({
        0: "",
        1: "",
        2: "",
        3: ""
    })

    // Handles

    return (
        <form>
            <input placeholder="Question" onChange={(e) => setQuestion(e.target.value)} />
            <ul>
                {Object.values(choices).map((choice, index) => (
                    <li key={index}>
                        <input
                            value={choice}
                            type="text"
                            onChange={(e) => choiceHandle(e, index)}
                        />
                       <button onClick={(e) => answerHandle(e, index)}>Set as Answer</button>
                    </li>
                ))}
                </ul>
        </form>
    )
}

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT