taile
taile

Reputation: 2776

React > How to set focus on the input field after adding a new row by using react-table

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.

enter image description here

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

Answers (3)

Parth Kale
Parth Kale

Reputation: 38

Plain and simple autoFocus worked for me in the text box.

Upvotes: 0

Mohamed Wagih
Mohamed Wagih

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);
  };

Edit Editable with react-table

I used requestAnimationFrame because I was manipulating the DOM, Checkout this answer for more details.

Upvotes: 3

atadnmz
atadnmz

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.

OR

You can convert your EditTable component to classed based comp.

Upvotes: 1

Related Questions