Reputation: 2776
I decided to use react-table
to build the grid.
Just one thing to have better UI, that is I want to focus on the input field of the new item after clicking on the add new button.
I intend to use ref
but have no idea how fowardRef
to the child item
Here is my example use of react-table:
https://codesandbox.io/s/beautiful-proskuriakova-lpfxn
In this case, I want to focus on the field First Name
after adding a new row.
UPDATED:
I am able to focus on the input by using autoFocus
support by native HTML.
The answer here
But I still want to handle focus by using React Ref
Upvotes: 3
Views: 9025
Reputation: 1456
I used plain JavaScript
to acheive your goal
const setFocus = () => {
//Add id to the table
document.getElementsByTagName("TABLE")[0].setAttribute("id", "mytable");
//table > tbody > tr (latest added row) > td (first cell in the row) > input
let cell = document.getElementById("mytable").lastElementChild
.lastElementChild.firstElementChild.children[0];
cell.focus();
};
const addNew = () => {
setData(old => [...old, {}]);
window.requestAnimationFrame(setFocus);
};
I used requestAnimationFrame
because I was manipulating the DOM, Checkout this answer for more details.
Upvotes: 3
Reputation: 311
You are trying to apply forwardRef()
on functional component and React doc says
You may not use the ref attribute on function components React ref doc
You can use useImeprativeHandle()
which can be;
const Table = React.forwardRef((props, ref) => {
const inputRef = React.useRef();
React.useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}), []);
return <Editable ref={inputRef} {...props} />;
}
Now you are able to reach ref with creating ref and call the imperative's method. I did not look how to focus your element but you can handle forwardRef
problem by using imperativeHandle.
You can convert your EditTable component to classed based comp.
Upvotes: 1