Sometimes, we want to update array state in React Native.
In this article, we’ll look at how to update array state in React Native.
How to update array state in React Native?
To update array state in React Native, we can call the state setter function with a function that returns the new array we want.
For instance, we write:
import * as React from 'react';
import { TextInput, Text, View } from 'react-native';
export default function App() {
const [arr, setArr] = React.useState(['foo', 'bar', 'baz']);
return (
<View>
{arr.map((a, i) => {
return (
<TextInput
value={a}
key={i}
onChangeText={(t) => {
setArr((arr) => {
const newArr = [...arr];
newArr[i] = t;
return newArr;
});
}}
/>
);
})}
<Text>{arr.join(', ')}</Text>
</View>
);
}
to define the arr
state with useState
.
Then we call arr.map
with a callback that renders a TextInput
.
Next, we set onChangeText
to a function that calls setArr
with a callback that updates the arr
array.
In the function, we make a copy of arr
and assign it to newArr
.
Then we assign newArr[i]
to the input value t
.
And then we return newArr
.
As a result, when we type something into the text input, we see the Text
display change to the typed value.
Conclusion
To update array state in React Native, we can call the state setter function with a function that returns the new array we want.