- React Material:UI Cookbook
- Adam Boduch
- 225字
- 2021-06-24 15:49:40
How to do it...
Let's say that you have an API function that fetches content based on an index value. For example, if the first panel is expanded, the index value will be 0. You need to be able to call this function when the panel is expanded, supplying the corresponding index value. Here's what the code looks like:
import React, { useState, Fragment } from 'react';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import Typography from '@material-ui/core/Typography';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
const fetchPanelContent = index =>
new Promise(resolve =>
setTimeout(
() =>
resolve(
[
'First panel content...',
'Second panel content...',
'Third panel content...',
'Fourth panel content...'
][index]
),
1000
)
);
export default function LazyLoadingPanelContent() {
const [panels, setPanels] = useState([
{ title: 'First Panel Title' },
{ title: 'Second Panel Title' },
{ title: 'Third Panel Title' },
{ title: 'Fourth Panel Title' }
]);
const onChange = index => e => {
if (!panels[index].content) {
fetchPanelContent(index).then(content => {
const newPanels = [...panels];
newPanels[index] = { ...newPanels[index], content };
setPanels(newPanels);
});
}
};
return (
<Fragment>
{panels.map((panel, index) => (
<ExpansionPanel key={index} onChange={onChange(index)}>
<ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
<Typography>{panel.title}</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<Typography>{panel.content}</Typography>
</ExpansionPanelDetails>
</ExpansionPanel>
))}
</Fragment>
);
}
Here's what the four panels look like when the screen first loads:

Try expanding the first panel. It expands right away but, for about one second, there's nothing there. Then the content appears:
