I am making a page for a react application that receives data and generates menus from that data. Each request received has data on an arbitrary number of ‘systems’ and I would like to generate a collapsible menu for each. Apologies if this kind of question has been asked before, I searched google but couldn’t find anything.
Obviously the traditional solution of a collapsible menu in react is to create a variable to store the state and to use that to toggle the menu’s visibility, but I cannot do that as I have an arbitrary number of menus. I tried setting up a dictionary of booleans to keep track of the state for each:
function Systems(props) {
const states = {};
return (
<div className={styles.formContainer}>
<p className={styles.formContainerLabel}>{props.type.toUpperCase()}</p>
{Object.keys(System_Definitions[props.type]).map((key) => {
const system = System_Definitions[props.type][key];
states[key] = false;
function toggleMenu() {states[key] = !states[key];}
return (
<div className={styles.formContainer}>
<p className={styles.formContainerLabel} onClick={toggleMenu}>
{key.toUpperCase() + ' - ' + system.label.toUpperCase()}</p>
<div id={key} className={states[key] ? '' : styles.formContainerContentHidden}>
<TextInput label={'Life'} name={'life'} placeholder={system.life} />
</div>
</div>
);
})}
</div>
);
}
But that did not work as react is not keeping track of the states so it does not update the boolean on click, and never opens the menus, which is what I have observed. I also tried adding a tag to add an event listener to the element to toggle the content:
function Systems(props) {
return (
<div className={styles.formContainer}>
<p className={styles.formContainerLabel}>{props.type.toUpperCase()}</p>
{Object.keys(System_Definitions[props.type]).map((key) => {
const system = System_Definitions[props.type][key];
return (
<div className={styles.formContainer}>
<p id={key + 'button'} className={styles.formContainerLabel}>
{key.toUpperCase() + ' - ' + system.label.toUpperCase()}</p>
<div id={key + 'content'} className={styles.formContainerContentHidden}>
<TextInput label={'Life'} name={'life'} placeholder={system.life} />
</div>
<script>
document.getElementByID({key} + 'button').addEventListener('click', () => {
document.getElementById(key + 'content').className = ''
})
</script>
</div>
);
})}
</div>
);
}
But I get a runtime error: ‘Cannot set properties of null (setting ‘className’)’, which I do not understand, since this script should not be executing until the elements have been loaded, since it is after the elements in question. Any help is appreciated!