0

I'm building a project in react native. I have a dynamic list of players, that I want the user to be able to edit.

const [players, setPlayers] = useState(['']);
function addPlayer() {
 setPlayers([...players, '']);
}
...
<List>
 { players.map(player => (
 <MyInput ...>
 )}
</List>

What I want to achieve is this:

  1. User enters name
  2. User presses enter
  3. We call addPlayer which adds a player
  4. New input appears and gets focused on (by other functions).

What I get is this:

  1. User enters name
  2. User presses enter
  3. We call addPlayer which adds a player
  4. The Keyboard starts closing for a split second and then opens back up when the new input appears.

I have set blurOnSubmit to false on my inputs. In my opinion what happens is that the list gets rerendered, causing the keyboard to dismiss itself. Then when the setPlayers finishes executing (it's async), the focus function gets called

useEffect(() => {
 if (lastRef.current) {
 lastRef.current.focus();
 }
}, [players]);

What is the best way to stop the list from rerendering so that the keyboard can stay open the whole time ? Thanks !

asked Aug 30, 2022 at 19:09
2
  • 2
    You should check these threads, maybe they can help you achieve what you want to do: Thread 1, Thread 2. Commented Aug 30, 2022 at 19:26
  • @ivanatias thanks for the links, but I already saw a lot of threads including the second one you sent and they didn’t help. I’ve managed to find a workaround solution that I will post in an answer Commented Aug 31, 2022 at 9:55

1 Answer 1

0

In the end I cheated, I added an input that’s sitting right outside the list. I can control whether it’s shown or not, it’s content, as well as it’s color with other state variables. That way when a player is added the list rerenders but doesn’t affect my input, and my keyboard doesn’t move. From a users POV it looks exactly the same as it did before, as if he’s editing items directly in the list.

answered Aug 31, 2022 at 9:58
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.