reactjsautofocus

How to autoFocus on list item after deleting an item?


I have this react code on Stackblitz where autoFocus works when a new item is added to the list but the same doesn't work when an item is deleted.

I need to find a solution where the last item remains in autoFocus when any item is deleted from the list.


Solution

  • You could use an array of refs to manage your inputs :

    import React, { Component, useState, useCallback } from 'react';
    import { render } from 'react-dom';
    import Hello from './Hello';
    import './style.css';
    
    class App extends Component {
      constructor() {
        super();
        this.state = {
          name: 'React'
        };
      }
    
      render() {
        return (
          <div>
            <Hello name={this.state.name} />
            <InputList />
          </div>
        );
      }
    }
    
    function InputList() {
      const refs = React.useRef([]);
      const [items, setItems] = useState([]);
      const add = useCallback(() => setItems([...items, {id: '1'}]), [items]);
      const ondelete = useCallback(() => {
        const index = items.length -1;
    
        if (index - 1 >= 0) {
          refs.current[index - 1].focus();
        } 
    
        setItems(items.splice(1));
      });
    
    
      return (
        <div>
          {items.map((item,i) => <input ref={e => refs.current[i] = e} key={item.i} autoFocus={i === items.length - 1 ? true : false}/>)}
          <button onClick={add} type="button">Add</button>
          <button onClick={ondelete} type="button">Delete</button>
        </div>
      );
    }
    
    render(<App />, document.getElementById('root'));
    
    

    I added the array of refs and modified your onDelete method to focus the correct input.