Material-Table AutoFocus on Row Add

Material-Table is a react data table based on Material-UI. It is quick to implement and will feel familiar to any developer experienced with React and MUI. It is also relatively easy to customize, such as adding autoFocus to the first input when adding a new row to a table.

I recently was using an editable material-table and noticed that I had to make an annoying extra click after adding a row before I could start typing in data. I’ll show in this article how I overrode the first column component to add autoFocus.

Take a look at this Code Sandbox for the complete code. I’ll dive into some of the most important points below.

Requirements and how to add autoFocus to material-table

Material-Table requires @material-ui/core. It also uses @material-ui/icons, but if that is not available then material-table replaces the icons with text. In my codesandbox I controlled this by directly giving the table the icons I wanted to use.

If you are adding rows, that implies you want to make use of the ‘editable’ config. Take a look at the docs here for the starter code. That is what I used in the above codesandbox. Please note the following:

  • onRowAdd must return a promise – otherwise the table breaks
  • onRowUpdate and onRowDelete are required with onRowAdd – otherwise the table styling is off

The most important unique piece of code I wrote can be seen in the first element in the ‘columns’ config array. Notice that I overrode ‘editComponent’ and added a lambda function that returns an MUI <Input/> element.

editComponent: (editProps) =>  (
      <Input
         autoFocus={true}
         onChange={(e) => editProps.onChange(e.target.value)}
      />
   )

The ‘onChange’ is necessary to return the <Input /> value to the onRowAdd callback properly; it won’t work without ‘onChange’.

Comment below with any good demos you’ve made using material-table.

Share this post:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.