NextJS store value between calls to component

Viewed 12

Doing my first NextJS project, and creating a static site from a headless CMS, so all data is populated from getStaticProps.

I have a component that maps sections returned from the CMS:

return (
  <div>
    {sections.map(section => <SectionType details={section} key={section.id} />)}
  </div>
)

Then for sections:

import Hero from './Hero';
import Section from './Section';

export default function SectionType({details}) {

    switch(details.__typename) {
        case 'HeroImageRecord':
            return <Hero { ...details }/>;
        case 'SectionRecord':
            return <Section { ...details } />;
        // more cases
        default:
            return null;
    }
}

The issue is, now I need to modify the className in a <Section based on the details of the preceding section. So, something like

export default function SectionType({details}) {
    let sectionICareAbout = false;

    switch(details.__typename) {
        case 'HeroImageRecord':
            return <Hero { ...details }/>;
        case 'SectionRecord':
            if (! sectionICareAbout) {
                if (details.nextOneMatters) sectionICareAbout = true;
                return <Section { ...details } />;
            } else {
                sectionICareAbout = false;
                return <Section extraClasses='foo bar' { ...details } />
            }

        // more cases
        default:
            return null;
    }
}

Obviously, the above won't actually work, because each map will be a new instance. I considered doing something with useState, but that doesn't make sense, since it's not the case that I want to re-render when state changes.

One thing I'm fairly certain I could do is, in the initial mapping in the parent, drill down into the details and set a variable at that level, but that doesn't feel right, either. It feels like it should be handled at the <SectionType component level.

Any ideas on how to solve this?

0 Answers
Related