I am trying to find a way to dynamically call a function given a string or reference a variable given a string. For instance:
import React, {useState} from 'react'
const array = [
{
text: 'count1',
setFunctionName: 'setCount1',
otherdata: {}
},
{
text: 'count2',
setFunctionName: 'setCount2',
otherdata: {}
}
]
const myFunction = () => {
const [count1, setCount1] = useState(0)
const [count2, setCount2] = useState(0)
return(
<div>
{array.map((item) => {
// I want to use item.text to reference the correct count variable
// I want to use item.setFunctionName to change the correct count
})}
</div>
)
}
The specific use case is I want to create a reusable sidebar menu where the data for the links are stored in an array of objects in a separate file. Some of the menu items will have collapsable submenus and I need to manage the opening and closing of the submenus using state. example:
import { Button, Collapse } from 'react-bootstrap'
function Example() {
const [open, setOpen] = useState(false);
return (
<>
<Button
onClick={() => setOpen(!open)} //**I want to dynamically set this when mapping over the array**
>
click
</Button>
<Collapse in={open}> //**I want to dynamically set this when mapping over the array**
<div id="example-collapse-text">
This is example collapsed text
</div>
</Collapse>
</>
);
}