Sepcio
Sepcio

Reputation: 255

React - render component inside accordion that was created in loop

I'm looking for any smart way to acheive below scenario:

I have a component that creates accordion in loop by given array of data. Single accordion looks like:

            <Accordion expanded={expanded === 'panel1'} onChange={handleChange('panel1')}>
                <AccordionSummary
                expandIcon={<ExpandMoreIcon />}
                aria-controls={"${id}-content"}
                id={"${id}-header"}
                >
                <Typography sx={{ width: '33%', flexShrink: 0 }}>
                    {status}
                </Typography>
                <Typography sx={{ color: 'text.secondary' }}>
                    {rID}
                </Typography>
                </AccordionSummary>
                <AccordionDetails>
                <Typography>
                    <BookingsDetails rID={rID} />
                </Typography>
                </AccordionDetails>
            </Accordion>

And onChange func:

const handleChange = (panel) => (event, isExpanded) => {
  setExpanded(isExpanded ? panel : false);
};

(I'm using Accordion from MUI.com)

Here is my problem. If I will have 1000+ records that will create 1000+ accordion's row during the loop, React will populate 1000+ times data in <BookingsDetails rID={rID} /> in advance that is not efficient.

What I want to acheive is:

Render <BookingsDetails rID={rID} /> component only once and only inside that accordion that was expanded by onChange method.

Now it's render inside each accordion which is wrong.

Can someone give me a tip how to do that?

Upvotes: 0

Views: 936

Answers (1)

Emanuele Scarabattoli
Emanuele Scarabattoli

Reputation: 4489

Well you can render your component conditionally, depending on the expanded panel, so:

{expanded === "panel1" ? <BookingsDetails rID={rID} /> : undefined}

I also suggest to change your handleChange function in this way:

setExpanded(isExpanded ? panel : undefined); // Or an empty string

To avoid mixing a boolean with something that should be a string or something not defined.

Upvotes: 1

Related Questions