I've created a project where I call an API to list all of the countries in the world and some facts about them. I have each country on a different card, and I want the card to say the country's name on the front and then flip to the back and show the country's continent and language when the user clicks the card. The problem is that when the user clicks the card, all of the cards flip. I realize now that I need to use id or something similar to target specific cards, but I can't figure out how.
What I've tried: There are various versions of this question on here and elsewhere, but often the code is much longer and it's harder to follow the advice, and some of those deal with changing the CSS or situations different from what I'm trying to do. I tried to create a state of 'clickedArray' to create an array that shows true of false for if any specific index is clicked, but I couldn't figure out where I could call a method that fills that array, and also I don't know if that's the correct strategy anyway.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
loading: true,
clicked: false
}
}
componentDidMount() {
fetch('https://restcountries.eu/rest/v2/all')
.then(response => response.json())
.then(json => this.setState({data: json}));
this.setState({loading: false});
}
clickHappens = () => {
this.setState({clicked: this.state.clicked ? false : true});
}
render() {
return (
<div className="container">
{this.state.data?.length > 0 && this.state.data.map((item, id) => (
<div className="box" key={id} onClick={this.clickHappens}>
{this.state.clicked === false ?
<Countryname name={item["name"]}/>
:
<Countryinformation continent={item["subregion"]} language={item["languages"][0]["name"]} />
}
</div>
))}
</div>
)
}
}
class Countryname extends React.Component {
render() {
return (
<h1>{this.props.name}</h1>
)
}
}
class Countryinformation extends React.Component {
render() {
return (
<>
<p>{this.props.continent}</p>
<p>{this.props.language}</p>
</>
)
}
}
export default App;