- React Material:UI Cookbook
- Adam Boduch
- 246字
- 2021-06-24 15:49:37
How it works...
The state defines everything about expansion panels. This includes the panel title, the panel content that's displayed when the panel is expanded, the disabled property, and whether or not the panel is hidden:
const [panels] = useState([
{
title: 'First Panel Title',
content: 'First panel content...'
},
{
title: 'Second Panel Title',
content: 'Second panel content...'
},
{
title: 'Third Panel Title',
content: 'Third panel content...'
},
{
title: 'Fourth Panel Title',
content: 'Fourth panel content...'
}
]);
The disabled property marks the panel as disabled. This means that the user can see the panel title, but it cannot be expanded. It's also visually marked as not being expandable. The hidden property ensures that the panel isn't rendered at all. This is useful for cases when you don't want the user to know about it at all.
Next, let's look at the code that renders each panel based on the component state:
{panels
.filter(panel => !panel.hidden)
.map((panel, index) => (
}>
{panel.title}
{panel.content}
))}
The filter() call removes panels from the array that have the hidden property set to true.
An alternative to using a hidden property to hide panels is removing them completely from the array. It really depends on personal preference—toggling a property value versus adding and removing values from an array.
Each panel is mapped to ExpansionPanel components using map(). The expansion panel uses an ExpansionPanelSummary component for the title and the content goes into the ExpansionPanelDetails component.