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: 45
Reputation: 396
here is a quick hack for it, remove any Enter char from the text
if (e.keyCode == 13) {
const index = state.findIndex((item) => item.id == e.target.id);
e.target.innerText = e.target.innerText.split('\n').join('')
// the rest of your code here
}
Upvotes: 1
Reputation: 1193
Add preventDefault
will prevent the default event occurring, in this case, the default event of the enter
key, which is creating a new line, will be stopped.
if (e.keyCode == 13) {
e.preventDefault(); //This should be at the top of the process.
//....
}
Upvotes: 1