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:
- User enters name
- User presses enter
- We call addPlayer which adds a player
- New input appears and gets focused on (by other functions).
What I get is this:
- User enters name
- User presses enter
- We call addPlayer which adds a player
- 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 !
-
2You should check these threads, maybe they can help you achieve what you want to do: Thread 1, Thread 2.ivanatias– ivanatias2022年08月30日 19:26:19 +00:00Commented 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 answerkoraljko– koraljko2022年08月31日 09:55:51 +00:00Commented Aug 31, 2022 at 9:55
1 Answer 1
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.