I am making td editable on click of edit button using contentEditable attribute, but focus is not happening
<tbody>
{props.tableData && props.tableData.map((row, ind) => {
return (
<tr key={row.id}>
<td>{row.id}</td>
{/* <td {...editObj}>{row.title}</td> */}
<td contentEditable={contentEditableId === row.id ? true : false} suppressContentEditableWarning={contentEditableId === row.id ? true : false}
>{row.title}</td>
<td style={{ "paddingRight": "20px" }} onClick={(e) => { editTd(e, row.id) }}>Edit</td>
<td onClick={() => props.deleteRowData(row.id)}>Delete</td>
</tr>)
})}
</tbody>
You will need to use refs (useRef hook) & then simply inputRef.current.focus();. I have made a codesandbox for <p>, you can replicate for <td>. Focus happens on load, can use the same approach for a button click etc -
import React, { useRef, useEffect } from "react";
import "./styles.css";
export default function App() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
// move caret to end
const textLength = inputRef.current.innerText.length;
const range = document.createRange();
const sel = window.getSelection();
range.setStart(inputRef.current.childNodes[0], textLength)
range.collapse(true)
sel.removeAllRanges()
sel.addRange(range)
}, [inputRef]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<div className="create-post">
<p
contentEditable
spellCheck="true"
placeholder="Write a new post here"
id="txtContent"
ref={inputRef}
>
Content Editable
</p>
</div>
</div>
);
}