I am making a memory type game as my first project in react native, but im running into some trouble with rerendering the children when the parent updates.
The child component:
import React from "react";
import { Pressable } from "react-native";
export default class GameCard extends React.Component
{
render()
{
return(
<Pressable
style={[{backgroundColor: this.props.isOpen ? this.props.color : 'coral'}, styles.card]}
onPress={this.props.handleClick}
/>
)
}
}
const styles = {
card: {
width: 77, height: 135,
margin: 10,
marginVertical: 30,
}
};
The parent:
import React, {Component, useState} from "react";
import {generateCards} from '../data/cards.js'
import Gamecard from "../components/GameCard.js";
import {FlatList, View, Text} from "react-native";
export default class Game extends Component {
state = {
score: 0,
currentSelection: [],
selectedPairs: [],
cards: []
}
componentDidMount() {
this.setState({
cards:generateCards(),
})
}
handleClick = id => {
let selectedPairs = [...this.state.selectedPairs];
let currentSelection = this.state.currentSelection;
let score = this.state.score;
let localCards = this.state.cards;
if(currentSelection.length < 2 && !currentSelection.includes(localCards[id]))
{
currentSelection.push(localCards[id]);
}
localCards[id].isOpen = true;
this.setState({
cards: localCards,
currentSelection: currentSelection
})
}
renderGameCard = ({item}) => {
return (
<Gamecard
color={item.color}
key={item.key}
isOpen={item.isOpen}
handleClick={this.handleClick.bind(this, item.key)}
/>
)
}
renderFlatList ()
{
let cardData = this.state.cards;
return (
<View style={{justifyContent: 'center', alignItems: 'center'}}>
<FlatList
data={cardData}
renderItem={this.renderGameCard}
numColumns={4}
extraData={this.state.currentSelection}
/>
</View>
)
}
render()
{
return this.renderFlatList();
}
}
Basically, when one of the children is clicked, i want to change its background color and perform some logic.
only problem is that the child component does not rerender when clicked, even though its isOpen property is updated in the parent state, can anyone explain / help me resolve this problem, Thanks in advance.