Reputation:
I am trying to pass a list of values to buttons. On Clicking the buttons a modal with the specifically mapped value should appear but in my case only the last value (3) in my array appears in all modals... How should I fix it ?
state = {
open: false,
stationData : [
{ id:1, number:'1' },
{ id:2, number:'2' },
{ id:3, number:'3' }
],
};
handleOpen = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
render() {
const {stationData} = this.state;
{stationData.map((station,index) => (
<div key={index}>
<Button variant="contained" color="primary" style={styles.button} onClick={this.handleOpen}>
{station.number}
</Button>
<Modal
open={this.state.open}
onClose={this.handleClose}
aria-labelledby={index}
aria-describedby={index}
>
<div style={styles.modal}>
{station.number}
</div>
</Modal>
</div>
))}
}
check out on this code sandbox
Upvotes: 3
Views: 7204
Reputation: 5742
You are creating three different modals in your stationData.map()
function and each one of them depend on a single state this.state.open
. So whenever a button is pressed all three of them is getting opened and you are seeing the last one on top. So 3 is always visible.
What you should do is- create only one modal and keep track of which button is pressed in a new state this.state.stationNumber
. That way, the only modal will fire and it will know what to render from the state.
Here is your modified code, I have added comments where necessary:
class Dashboard extends React.Component {
state = {
open: false,
stationNumber: null,
stationData: [
{ id: 1, number: "1" },
{ id: 2, number: "2" },
{ id: 3, number: "3" }
]
};
handleOpen = stationNumber => () => {
// get which button was pressed via `stationNumber`
// open the modal and set the `stationNumber` state to that argument
this.setState({ open: true, stationNumber: stationNumber });
};
handleClose = () => {
this.setState({ open: false });
};
render() {
const { stationData } = this.state;
return (
<div style={styles.wrapper}>
<div style={styles.body}>
<Paper square elevation={0} style={styles.container}>
{stationData.map((station, index) => (
<div key={index}>
<Button
variant="contained"
color="primary"
style={styles.button}
// pass which button was clicked as an argument
onClick={this.handleOpen(station.number)}
>
{station.number}
</Button>
</div>
))}
</Paper>
{/* add only one modal */}
<Modal open={this.state.open} onClose={this.handleClose}>
{/* display the content based on newly set state */}
<div style={styles.modal}>{this.state.stationNumber}</div>
</Modal>
</div>
</div>
);
}
}
Upvotes: 9