Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically call a function/variable using a string inside a function Javascript/React

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>
        </>
      );
    }
like image 988
CherryPoppins Avatar asked Feb 21 '26 13:02

CherryPoppins


1 Answers

Probably the best way to achieve this would be to use a reducer.

https://reactjs.org/docs/hooks-reference.html#usereducer

Something like this maybe?

const initialState = {count1: 0, count2: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'setCount1':
      return {
        ...state,
        count1: action.value
      };
    case 'setCount2':
      return {
        ...state,
        count2: action.value
      };
    default:
      throw new Error();
  }
}

const array = [
  {
    text: 'count1',
    setFunctionName: 'setCount1',
    otherdata: {}
  },
  {
    text: 'count2',
    setFunctionName: 'setCount2',
    otherdata: {}
  }
]

const myFunction = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return(
     <div>
       {array.map((item) => {
          return <a onClick={ () => dispatch({ type: item.setFunctionName, value:3 }) }>{state[item.text]} <a/>
        })}
     </div>
  )
}
like image 98
Devon Ray Avatar answered Feb 24 '26 02:02

Devon Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!