I'm new to React and I'm having trouble setting state for an array of objects. I want each object to be able to reflect and "clicked" state individually. Below is my code.
const pictures = [
{
photo: 'https://cdn.images.dailystar.co.uk/dynamic/1/photos/755000/620x/cristiano-ronaldo-net-worth-how-much-madrid-player-worth-695569.jpg?r=5c053f491050f',
id: 0,
clicked: false
}, {
photo: 'https://www.tsn.ca/polopoly_fs/1.912227!/fileimage/httpImage/image.jpg_gen/derivatives/landscape_620/antoine-griezmann.jpg',
id: 1,
clicked: false
}, {
photo: 'https://e00-marca.uecdn.es/assets/multimedia/imagenes/2018/02/03/15176565269601.jpg',
id: 2,
clicked: false
}, {
photo: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTqa94bKUtifeRx2kxVEZFgTNx3JjEgD1ymNqRP8k8Au9zmLZiz',
id: 3,
clicked: false
},
]
export default class picRender extends Component {
state = {
clicked: false
}
handleClick = (event) => {
if (this.state.clicked === false) {
this.setState({clicked: true});
console.log(event.target.getAttribute('data-key') + " state changed to clicked");
console.log(this.state.clicked);
} else if (this.state.clicked === true) {
console.log('THIS HAS BEEN CLICKED!');
}
}
render() {
return pictures.map(pic => <img
className="photo"
data-key={pic.photo}
key={pic.id}
src={pic.photo}
onClick={this
.handleClick.bind(this)}></img>);
}
}
Each time one of the pictures is clicked, the entire array's state is changed to "true." I'm not sure how to reflect each individual object's change of state.
imginto another component and add on click there, so each item in array would have it's own state