I need to select images in an image grid. Currently, I can only select one image at a time. When selecting one, the other unselects. I'd like to select every image I want (many images selected at a time). I can't activate a isToggle boolean on each element with onClick event.
class Gallery extends Component{
constructor(props) {
super(props);
this.state = {
//isToggleOn: true,
selected: '',
};
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleClick = key => {
this.setState(state => ({
//isToggleOn: !state.isToggleOn,
selected: key,
}));
//console.log(this.state)
}
render(){
//const classes = useStyles();
return (
<Container>
<Row >
<Col>
<div style={styles.root}>
<GridList cellHeight={160} style={styles.gridList} cols={3}>
{tileData.map((tile,i) => (
<GridListTile key={i} cols={tile.cols || 1} onClick={() => this.handleClick(tile)} >
<img src={tile.img} alt={tile.title} style={this.state.selected === tile ? styles.inputClicked:styles.inputNormal} />
</GridListTile>
))}
</GridList>
</div>
</Col>
</Row>
</Container>
);
}
}
export default Gallery;
I can only select one image at a time. I expect to select many at a time.
When the tile gets clicked, you need to add to an array of selected tiles like this:
handleClick = tile => {
this.setState({
selected: this.state.selected.concat([tile]),
});
}
then when rendering, you can check if the tile is selected something like this:
<img src={tile.img} alt={tile.title} style={isSelected(this.state.selected, tile) ? styles.inputClicked:styles.inputNormal} />
with:
isSelected = (selected, tile) => {
// some logic to check that the tile is already selected e.g.
return selected.find(tileItem => tileItem.title === tile.title)
}
Ensure to initialise your selected state to [] in constructor :
this.state = {
selected: [],
};
UPDATE:
If you want to remove tiles too, you'd have to do something like this:
handleClick = tile => {
const { selected } = this.state;
if(selected.find(item ==> item.title === tile.title)) {
// need to remove tile
this.setState({
selected: selected.filter(item => item.tile !== tile.title),
});
} else {
this.setState({
selected: this.state.selected.concat([tile]),
});
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments