#How to keep focus on TextField after re-render.

2 messages · Page 1 of 1 (latest)

uneven hedge
#

So I currently have this:

export const CollectionEdit = () => {
    const [hunt, setHunt] = useState<Hunt>({} as Hunt);
        //.....
    const handleQuestionTitleChange = (
        e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
        question: Question,
    ) => {
        setHunt({
            ...hunt, questions: hunt.questions.map((q) => {
                if (q === question) {
                    return { ...q, question: e.target.value };
                }
                return q;
            }),
        });
    };

        return (
              ...
                  {
            hunt.questions && hunt.questions.length ? (
                hunt.questions.map((q) => {
                    return (
                        <QuestionBox
                            titleChange={handleQuestionTitleChange}
                            key={q.question}
                            q={q}
                        />
                    );
                })
            ) : (<></>)
        }
              ...
        )
}

Types:

export type Hunt = {
    id?: string,
    title: string,
    description: string
    questions: Question[]
}

export type Question = {
    question: string,
    answers: Answers[]
}

export type Answers = {
    option: string,
    correct: boolean
}

The QuestionBox component is simply a box with a input field. When I change the input field it re-renders the components and can no longer focus that title that I tried to edit. Is there any workaround for this or perhaps another solutions to edit individual questions?

#

I was thinking making a seperate state for the questions however that will give the problem that there needs to be a solution to pushing to that state on save