Reputation: 936
When you hit enter a new filed will be created but the problem is the focus
and the focus will move to the newly created filed, but the problem is : its leave an enter space in the previous
field
`
import React, { useState } from "react";
import "./styles.css";
export default function App() {
let elements = [
{ id: 0, text: "first", autoFocus: true },
{ id: 1, text: "second", autoFocus: true },
{ id: 2, text: "third", autoFocus: true }
];
const [state, setstate] = useState(elements);
function handChange(e) {
if (e.keyCode == 13) {
const index = state.findIndex((item) => item.id == e.target.id);
//i'm using autoFocus to move the focus (I-beam pointer) to the nex field.
//but i still get errors with it
Object.assign(state, (state[index].autoFocus = false));
setstate((pre) => {
return [
...pre.slice(0, index + 1),
{ id: 3, text: "xxx", autoFocus: true },
...pre.slice(index + 1, state.length)
];
});
setTimeout(() => {
document.getElementById(index + 1).focus();
}, 0);
}
}
return (
<div className="App">
{state.map((e) => (
<div contentEditable="true" id={e.id} onKeyUp={handChange}>
{e.text}
</div>
))}
</div>
);
}
on codesandbox
Upvotes: 0
Views: 270
Reputation: 1
Try out to clone the state then map it by updating the autoFocus
and text
properties :
function handChange(e) {
if (e.keyCode === 13) {
let _state = [...state];
setstate(
_state.map((item) => {
if (+e.target.id === +item.id) {
return {
...item,
autoFocus: false
};
} else if (+e.target.id + 1 === +item.id + 1) {
return {
...item,
autoFocus: true,
text: "xxx"
};
} else {
return item;
}
})
);
}
}
return (
<div className="App">
{state.map((e) => (
<input
focus={e.autoFocus}
contentEditable="true"
id={e.id}
onKeyUp={handChange}
value={e.text}
/>
))}
</div>
);
Upvotes: 1
Reputation: 6712
The focus attribute will not work on a div
element.
You should use an input
element with the autoFocus
attribute in React.
<input autoFocus={e.autoFocus} value={e.text} id={e.id} onKeyUp={handChange}/>
Upvotes: 1