I am using Material-UI for UI design. I am using an expansion panel with checkbox integrated into it.
Please find below code,
<ExpansionPanel
expanded={expanded === item.description}
onChange={this.handleChange(item.description)}
>
<ExpansionPanelSummary expandIcon={<ExpandMoreIcon/>}>
<Grid item xs={1}>
<Checkbox
value="checkedB"
color="primary"
/>
</Grid>
<Grid item xs={2}>
<Typography className={classes.heading}>
{item.description}
</Typography>
</Grid>
<Typography className={classes.desc}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Suspendisse malesuada lacus ex,
sit amet blandit leo lobortis eget.
</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Suspendisse malesuada lacus ex,
sit amet blandit leo lobortis eget.
</ExpansionPanelDetails>
</ExpansionPanel>
But I am facing one issue, when I check or uncheck the checkbox, expansion panel expands or collapse. I want to avoid any action on expansion panel due to the checkbox. How can I achieve that?
Thanks in advance.
const [expanded, setExpanded] = React.useState(false);
<Checkbox
value="checked"
color="primary"
onClick={() => setExpanded(!expanded)}
/>
<ExpansionPanel expanded={expanded}>
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon />}
onClick={() => setExpanded(!expanded)}
>
ON CLICK OPEN
</ExpansionPanelSummary>
<ExpansionPanelDetails>
IS OPEN
</ExpansionPanelDetails>
</ExpansionPanel>
You can simply stop propagating an event:
function handleClickCheckbox(e) {
e.stopPropagation();
// do something
}
...
<Checkbox value="checkedB"
color="primary"
onClick={e => handleClickCheckbox(e)}
/>
https://codesandbox.io/s/431284p0m0
Or more simply:
<Checkbox value="checkedB"
color="primary"
onClick={e => {e.stopPropagation();}}
/>
For version: "@material-ui/core": "4.9.9"
If you add the onClick
only to the expandIcon
you are gonna lose all the space of the panel summary to be clicked, additionally, not all users are gonna know at first that they have to click the arrow icon to expand the panel, for that reason, is better to add the onClick event to the ExpansionPanelSummary
, by doing this the click event won't cover ExpansionPanelDetails and the entire ExpansionPanelSummary
can have its normal behavior to be clicked anywhere and to expand/collapse.
<ExpansionPanel expanded={isExpanded}>
<ExpansionPanelSummary expandIcon={<ExpandMore />} onClick={handleClickExpansion}>...</ExpansionPanelSummary>
<ExpansionPanelDetails>....</ExpansionPanelDetails>
</ExpansionPanel>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With