1

I have 3 different Accordions that a single state controls their open and close state like so:

 const [accordionOpen, setAccordionOpen] = useState({
    countryOfOriginAccordion: true,
    schoolAccordion: false,
    areaOfStudyAccordion: false,
  });

ideally, I am setting each state with their own function like this:

setAccordionOpen((previousState) => ({
                ...previousState,
                schoolAccordion: !accordionOpen.schoolAccordion,
              }))

I want to use a single function that changes this value in state dynamically:

1 Answer 1

2

You could do something like this:

const toggleAccordionOpen = (accordionName) => setAccordionOpen((prevState) => ({
  ...prevState,
  [accordionName]: !prevState[accordionName],
}));

// Example of usage
toggleAccordionOpen('countryOfOriginAccordion');

If you are using Typescript you can annotate the accordionName to a type union:

const ACCORDION_NAMES = {
  COUNTRY_OF_ORIGIN: 'countryOfOriginAccordion',
  SCHOOL: 'schoolAccordion',
  AREA_OF_STUDY: 'areaOfStudyAccordion',
} as const;

type AccordionNameGeneric<T> = T[keyof T];
type AccordionName = AccordionNameGeneric<typeof ACCORDION_NAMES>;

const toggleAccordionOpen = (accordionName: AccordionName) => 
...

And then call it like this:

toggleAccordionOpen(ACCORDION_NAMES.COUNTRY_OF_ORIGIN);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.