Answer the question
In order to leave comments, you need to log in
Why isn't the state updated?
I'm trying React, I want to write a card memory game. When you click on the card component, the text ( data ) does not appear, but if you try to log, the methods are executed. What could be the problem?
field.js
import React, {useState} from 'react';
import styled from "styled-components";
import Card from "./Card";
import {cardsData, shuffle} from "../common/cards.data";
const FieldGrid = styled.div`
display: grid;
grid-gap: 2rem;
grid-template-columns: repeat(4, 1fr);
`
const Field = () => {
const [cards, setCards] = useState(() => shuffle(cardsData))
const [isFlipped, setIsFlipped] = useState(Array<boolean>(cards.length).fill(false))
const handleFlip = (index: number) => {
isFlipped[index] = !isFlipped[index]
setIsFlipped(isFlipped)
}
return (
<FieldGrid>
{
cards.map((data, index) => {
return <Card key={index}
index={index}
isFlipped={isFlipped[index]}
data={data}
onClick={handleFlip}/>
})
}
</FieldGrid>
);
};
export default Field;
import React from 'react';
import styled from 'styled-components'
import CardProps from "../common/interfaces/card.props";
const CardWrapper = styled.div`
background: #fbfdfd;
border-radius: 12px;
width: 10rem;
height: 10rem;
padding: 3rem;
display: flex;
justify-content: center;
align-items: center;
box-shadow: 0 4px 8px 0 rgba(176, 192, 204, 0.2);
font-size: 3rem;
text-align: center;
transition: 150ms background-color ease;
cursor: pointer;
&:hover {
background: #f2f8f8;
}
`
const Card = (props: CardProps) => {
const handleClick = () => {
props.onClick(props.index);
};
return (
<CardWrapper onClick={handleClick}>
{props.isFlipped ? props.data : ""}
</CardWrapper>
);
};
export default Card;
export default interface CardProps {
data: string;
isFlipped: boolean;
index: number;
onClick: (index: number) => void;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question