I'm making a React application and I need a table where each row contains an input. For that, I'm using Material-UI and Formik, but I have a bug that anytime I type something in one of the inputs, I lose the focus of that input. I saw this bug a lot on the internet, I tried with adding keys, deleting keys, use defaultValue instead of value, and anything worked properly for me.
I've created a codesandbox for this: https://codesandbox.io/s/gracious-robinson-i69v3?file=/src/App.js
If anyone could help me I would really appreciate, I'm stuck with this problems for a few days.
CodePudding user response:
Everytime your MyInput
components rerenders, it key changes because it's non deterministic (it uses Math.random()
). Because of this, React will remove the existing DOM node and insert a new DOM node in it's place. Your browser now thinks it's an other element, so it does not put focus on that element.
CodePudding user response:
You don't have to set the key
property on every component. It's just needed where you output an array of elements, e.g. when using map
. So in your example only the Formik
component needs to have the key property set, because it's the parent of the other components inside the loop.
{companies.map((company, index) => (
<Formik
key={index}
initialValues={{
contact_name: company.contact_name || "",
contact_email: company.contact_email || ""
}}
onSubmit={(values) => {
console.log(values);
}}
>
{(formik) => (
...