简体   繁体   中英

React: Handling focus using array of useRef

I have created a basic Todo app but having a hard time in implementing proper focus into it. Following are the requirements for focus:

  1. Focus should be on the newly created input field when "Add" is clicked so the user can begin typing right away.

  2. On deleting an item "Button X", focus will move to the input field in the row which replaced the deleted row, nowhere if there are no fields left, or on the new last row if the last row was deleted.

  3. On moving an item up, focus should be placed on the newly moved field, and all associated buttons should move alongside the element. If a field is already at the top of a list, no reordering should occur, but focus should be transferred to the topmost field nonetheless.

  4. On moving an item down, same principle should apply here (focus should be placed on the field that is moved down). If its the last field, focus it nonetheless.

Here is my implementation.

App.js:

import React, { useState, useRef } from "https://cdn.skypack.dev/react@17.0.1";
import ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1";

const App = () => {
    const [myRows, setMyRows] = useState([]);
    const focusInput = useRef([]);

    const onAddRow = () => {
        setMyRows((prevRows) => {
            return [
                ...prevRows,
                { id: prevRows.length, text: "", up: "↑", down: "↓", delete: "X" },
            ];
        });
        focusInput.current[myRows.length - 1].focus();
    };

    const onMoveUp = (index) => (event) => {
        const currentState = [...myRows];
        if (index !== 0) {
            const prevObject = currentState[index - 1];
            const nextObject = currentState[index];
            currentState[index - 1] = nextObject;
            currentState[index] = prevObject;
            setMyRows(currentState);
        }
    };

    const onMoveDown = (index) => (event) => {
        const currentState = [...myRows];
        if (index !== myRows.length - 1) {
            const currObject = currentState[index];
            const nextObject = currentState[index + 1];
            currentState[index] = nextObject;
            currentState[index + 1] = currObject;
            setMyRows(currentState);
        }
    };

    const onDelete = (index) => (event) => {
        const currentState = [...myRows];
        currentState.splice(index, 1);
        setMyRows(currentState);
    };

    const onTextUpdate = (id) => (event) => {
        setMyRows((prevState) => {
            const data = [...prevState];
            data[id] = {
                ...data[id],
                text: event.target.value,
            };
            return data;
        });
    };
return (
        <div className="container">
            <button onClick={onAddRow}>Add</button>
            <br />
            {myRows?.map((row, index) => {
                return (
                    <div key={row.id}>
                        <input
                            ref={(el) => (focusInput.current[index] = el)}
                            onChange={onTextUpdate(index)}
                            value={row.text}
                            type="text"></input>
                        <button onClick={onMoveUp(index)}>{row.up}</button>
                        <button onClick={onMoveDown(index)}>{row.down}</button>
                        <button onClick={onDelete(index)}>{row.delete}</button>
                    </div>
                );
            })}
        </div>
    );
}

ReactDOM.render(<App />,
document.getElementById("root"))

In my implementation when I click Add, focus changes but in unexpected way (First click doesn't do anything and subsequent click moves the focus but with the lag, ie focus should be on the next item, but it is at the prior item.

Would really appreciate if someone can assist me in this. Thanks!

The strange behaviour that you observe is caused by the fact that state updates are asynchronous. When you, in onAddRow , do this:

focusInput.current[myRows.length - 1].focus()

then myRows.length - 1 is still the last index of the previous set of rows, corresponding to the penultimate row of what you're actually seeing. This explains exactly the behaviour you're describing - the new focus is always "one behind" where it should be, if all you're doing is adding rows.

Given that description, you might think you could fix this by just replacing myRows.length - 1 with myRows.length in the above statement. But it isn't so simple. Doing this will work even less well, because at the point this code runs, right when the Add button is clicked, focusInput hasn't yet been adjusted to the new length, and nor in fact has the new row even been rendered in the DOM yet. That all happens a little bit later (although appears instantaneous to the human eye), after React has realised there has been a state change and done its thing.

Given that you are manipulating the focus in a number of different ways as described in your requirements, I believe the easiest way to fix this is to make the index you want to focus its own piece of state. That makes it quite easy to manage focus in any way you want, just by calling the appropriate state-updating function.

This is implemented in the code below, which I got working by testing it out on your Codepen link. I've tried to make it a snippet here on Stack Overflow, but for some reason couldn't get it to run without errors, despite including React and enabling Babel to transform the JSX - but if you paste the below into the JS of your Codepen, I think you'll find it working to your satisfaction. (Or, if I've misinterpreted some requirements, hopefully it gets you at least a lot closer than you were.)

Rather than just leaving you to study the code yourself though, I'll explain the key parts, which are:

  • the introduction of that new state variable I just mentioned, which I've called focusIndex
  • as mentioned, the calling of setFocusIndex with an appropriate value whenever rows are added, removed or moved. (I've been trying to follow your requirements here and it seems to work well to me, but as I said, I may have misunderstood.)
  • the key is the useEffect which runs whenever focusIndex updates, and does the actual focusing in the DOM. Without this, of course, the focus will never be updated on calling setFocusIndex , but with it, calling that function will "always" have the desired effect.
  • one last subtlety is that the "always" I put above is not strictly true. The useEffect only runs when focusIndex actually changes, but when moving rows there are some situations where it is set to the same value it had before, but where you still want to move focus. I found this happening when clicking outside the inputs, then moving the first field up or the last one down - nothing happened, when we want the first/last input to be focused. This was happening because focusIndex was being set to the value it already had, so the useEffect didn't run, but we still wanted it to in order to set the focus. The solution I came up with was to add an onBlur handler to each input to ensure that the focus index is set to some "impossible" value (I chose -1, but something like null or undefined would have worked fine as well) when focus is lost - this may seem artificial but actually better represents the fact that when the focus is on no inputs, you don't want to have a "sensible" focusIndex, otherwise the React state is saying one of the inputs is focused, when none are. Note that I also used -1 for the initial state, for much the same reason - if it starts at 0 then adding the first row doesn't cause focus to change.

I hope this helps and my explanations are clear enough - if you're confused by anything, or notice anything going wrong with this implementation (I confess I have not exactly tested it to destruction), please let me know!

import React, { useState, useRef, useEffect } from "https://cdn.skypack.dev/react@17.0.1";
import ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1";

const App = () => {
    const [myRows, setMyRows] = useState([]);
    const focusInput = useRef([]);
    const [focusIndex, setFocusIndex] = useState(-1);

    const onAddRow = () => {
        setMyRows((prevRows) => {
            return [
                ...prevRows,
                { id: prevRows.length, text: "", up: "↑", down: "↓", delete: "X" },
            ];
        });
        setFocusIndex(myRows.length);
    };
  
    useEffect(() => {
        console.log(`focusing index ${focusIndex} in`, focusInput.current);
        focusInput.current[focusIndex]?.focus();
    }, [focusIndex]);

    const onMoveUp = (index) => (event) => {
        const currentState = [...myRows];
        if (index !== 0) {
            const prevObject = currentState[index - 1];
            const nextObject = currentState[index];
            currentState[index - 1] = nextObject;
            currentState[index] = prevObject;
            setMyRows(currentState);
            setFocusIndex(index - 1);
        } else {
            setFocusIndex(0);
        }
    };

    const onMoveDown = (index) => (event) => {
        const currentState = [...myRows];
        if (index !== myRows.length - 1) {
            const currObject = currentState[index];
            const nextObject = currentState[index + 1];
            currentState[index] = nextObject;
            currentState[index + 1] = currObject;
            setMyRows(currentState);
            setFocusIndex(index + 1);
        } else {
            setFocusIndex(myRows.length - 1);
        }
    };

    const onDelete = (index) => (event) => {
        const currentState = [...myRows];
        currentState.splice(index, 1);
        setMyRows(currentState);
        const newFocusIndex = index < currentState.length
            ? index
            : currentState.length - 1;
        setFocusIndex(newFocusIndex);
    };

    const onTextUpdate = (id) => (event) => {
        setMyRows((prevState) => {
            const data = [...prevState];
            data[id] = {
                ...data[id],
                text: event.target.value,
            };
            return data;
        });
    };

    return (
        <div className="container">
            <button onClick={onAddRow}>Add</button>
            <br />
            {myRows?.map((row, index) => {
                return (
                    <div key={row.id}>
                        <input
                            ref={(el) => (focusInput.current[index] = el)}
                            onChange={onTextUpdate(index)}
                            onBlur={() => setFocusIndex(-1)}
                            value={row.text}
                            type="text"></input>
                        <button onClick={onMoveUp(index)}>{row.up}</button>
                        <button onClick={onMoveDown(index)}>{row.down}</button>
                        <button onClick={onDelete(index)}>{row.delete}</button>
                    </div>
                );
            })}
        </div>
    );
}

ReactDOM.render(<App />,
document.getElementById("root"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM