I want to have a 2 dimensional array for the state. Once a user clicks on a touch area. It will update a value in this 2 dimensional array. For some reason, I got error with my code. The following are the constructor and the onPress function
export default class App extends Component<Props> {
constructor(Props){
super(Props);
this.state = {
test: 'U',
array: [
['n','n','n'],
['6','n','n'],
['n','n','n'],
]
};
}
onPress = (row,colum) => {
this.setState({
array[row][colum]: this.test
});
}
render() {
return (
<View style={styles.middleWrapper}>
<TouchableOpacity style={[styles.child]} onPress={this.onPress(1,0)}><Text> {this.state.array[1][0]}</Text></TouchableOpacity>
</View>
);
}
}
It seems the onPress method is not right. But I do not know what is not right. Please help. Thanks.
**
**
get the error:
\node_modules\react-native\scripts\App.js: Unexpected token, expected "," (38:11)
36 | onPress = (row, column) => () => {
37 | this.setState({
> 38 | array[row][colum]: this.test
| ^
39 | })
40 | }
41 |
The Unexpected token syntax error is from the object in your setState call. The key needs to be wrapped in another set of square brackets:
this.setState({
[array[row][column]]: this.test
})
This doesn't solve the problem, though.
// Create a copy of the state array so that you don't mutate state.
const array = [...this.state.array];
// Update the copy with the new value.
array[row][column] = this.test;
// Replace the state array with the new copy.
this.setState({ array });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With