I have this component that renders another component with the data and input fields. Upon typing in that component it loses focus since it re-renders the components.
The main component:
export const CollectionEdit = () => {
const [hunt, setHunt] = useState<Hunt>({} as Hunt);
useEffect(() => {
//Fetch and setState here
}, []);
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 (
<Box component="div" sx={{ backgroundColor: "#faf5f7" }}>
{
hunt.questions && hunt.questions.length ? (
hunt.questions.map((q) => {
return (
<QuestionBox
key={q.question}
question={q}
titleChange={handleQuestionTitleChange}
/>
);
})
) : (<></>)
}
</Box>
);
};
The QuestionBox
component:
type Props = {
question: Question,
titleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, question: Question) => void
}
export const QuestionBox = ({ question, titleChange }: Props) => {
return (
<Box sx={{ backgroundColor: "#fff", width: "100%", p: 4, mt: 4 }}>
<TextField
variant="standard"
value={question.question}
onChange={(e) => titleChange(e, question)}
fullWidth
/>
</Box>
);
};
Now I know that this is caused by the re-rendering of the components. However I can't seem to come up with an solution. I tried out this answer too but I think I'm missing something. In the meanwhile I'm trying out a solution with useRef()
to see if i can keep the focus