przełączanie indywidualnego elementu za pomocą mapy w React
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
loading: true,
clicked: null // <-- start with null state
}
}
componentDidMount() {
fetch('https://restcountries.eu/rest/v2/all')
.then(response => response.json())
.then(data => this.setState({ data }))
.finally(() => this.setState({ loading: false }));
}
clickHappens = (id) => () => {
this.setState(prevState => ({
clicked: prevState.clicked === id ? null : id, // <-- toggle back to null or to new id
}));
}
render() {
return (
<div className="container">
{this.state.data?.map((item, id) => (
<div
className="box"
key={id}
onClick={this.clickHappens(id)} // <-- pass id to toggle
>
{this.state.clicked === id ? // <-- check id match
<Countryinformation
continent={item["subregion"]}
language={item["languages"][0]["name"]}
/>
:
<Countryname name={item["name"]}/>
}
</div>
))}
</div>
)
}
}
Balo