0

I have a few elements that are essentially the same that I'm trying to refactor to be neater. The main difference is that they refer to different variables of a similar format.

For example:

(!editingTelephone && telephone === '') && 'No landline number added'}

and

(!editingMobile && mobile === '') && 'No mobile number added'

I'm wanting to be able to pass a string such as 'telephone' or 'mobile' to a function to do the construction of the whole component that will fill in all of the relevant variable names and content.

My struggle is dynamically constructing the variable names such that they call correctly...

I know that eval() is available to use when it comes constructing variable names via strings, but I also know that this is warned against from using, from a security perspective... I'm just wondering if there is something else, safer that I can use, or would this be fine to use in React from a security perspective in this instance given that I'm not exactly exposing anything major?

physicsboy
  • 5,656
  • 17
  • 70
  • 119
  • 4
    Mostly answered by ["Variable" variables in JavaScript](https://stackoverflow.com/q/5187530) However, I really don't see why you'd want to do any sort of dynamic variables here, since you have *three* things that need to be edited, not just `mobile` or `telephone`. Maybe just make a function `(editing, value, message) => (!editing && value === '') && message` then feed it the values. No need for dynamic construction of code or trying to magically accessing things by name from lookups. – VLAZ Jan 09 '23 at 11:08

1 Answers1

0

You need to store info in some other object (window by default) and then:

const store = {mobile:undefined, phone:"001002003"}

function test(name) {
   console.log(store[name]);
}

//Test:
test("mobile") ;
Jan Pfeifer
  • 2,854
  • 25
  • 35