I am trying to make a flipped set of cards in React. You can see my code below. When I click on the card, they all flipped, but my goal is to flip only those that i clicked on. How can I do this?
This is my card component:
import React from 'react';
export default class Card extends React.Component {
render() {
let className = this.props.condition ? 'card-component flipped' : 'card-component';
return (
<div onClick={this.props.handleClick} className={className}>
<div className="front">
<img src={this.props.image} alt="card"/>
</div>
<div className="back">
</div>
</div>);
}
}
Here is my Deck component:
import React from 'react';
import Card from './Card.js';
const cardlist = require('../cardlist').cardlist;
export default class Deck extends React.Component{
constructor(props) {
super(props);
this.state = {flipped: false};
}
handleClick() {
this.setState({flipped: !this.state.flipped});
}
render() {
const list = this.props.cards.map((card, index) => {
return <Card
key={index}
handleClick={this.handleClick.bind(this)}
condition={this.state.flipped}
image={cardlist[card].path}
/>});
return(
<ul>
{list}
</ul>)
}
};
Thank you!
To toggle a class on click in React: Set the onClick prop on the element. Store the active state in a state variable. Conditionally add the class using a ternary operator.
To toggle class on click with React, we can set the className prop. to create the MyComponent component. In it, we have the isActive state. We set it with the setActive function in the toggleClass function.
You can make use of indexes.
export default class Deck extends React.Component{
constructor(props) {
super(props);
//flipped true nonflipped false
this.state = {
flipStatus : props.cards.map((element) => false)
}
handleClick(index) {
const newflipStatus = [...this.state.flipStatus]
newflipStatus[index] = !this.state.flipStatus[index]
this.setState({flipStatus: newflipStatus);
}
render() {
const list = this.props.cards.map((card, index) => {
return <Card
key={index}
handleClick={this.handleClick.bind(this)}
condition={this.state.flipped}
index={index}
image={cardlist[card].path}
flipped=this.state.flipStatus[index]
/>});
return(
<ul>
{list}
</ul>)
}
};
here is your card component
export default class Card extends React.Component {
render() {
let className = this.props.condition ? 'card-component flipped' : 'card-component';
return (
<div onClick={() => this.props.handleClick(this.props.index)} className={className}>
{!flipped && <div className="front">
<img src={this.props.image} alt="card"/>
</div>}
{flipped && <div className="back">
</div>}
</div>);
}
}
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