0

I'm trying to map an array and reference the .map() parameters 'button' and 'i', in my React Native JSX. Feel like I've tried everything at this point. How do I correctly reference button and i as an item in my styles object within a JSX style prop? is this not possible?

{buttonSet.map(function(button, i) {
  let pleaseHelpMe = button + `${i}`;
  return (
    <TouchableHighlight
    style={[styles.abacusButton, styles.pleaseHelpMe]}
    ...
    >
      <Text>X</Text>
    </TouchableHighlight>
  );
})}
JMcFar
  • 291
  • 2
  • 13
  • 1
    you have a typo `${i]}` has a closing array bracket... change to `${i}`. Also can you give an example of what `buttonSet` is? And also what your `styles` are? Why would you be defining a style for every button by their index? – John Ruddell Jul 22 '19 at 02:17
  • `i]` is invalid syntax and `pleaseHelpMe` is not the same as `styles.pleaseHelpMe` – slebetman Jul 22 '19 at 02:20
  • @ slebetman, sorry, that typo doesn't exist in my actual code, just my simplification here. I'll edit it. – JMcFar Jul 22 '19 at 02:21
  • 1
    If you want to dynamically reference a key in an object then you access it via, `styles[pleaseHelpMe]` – John Ruddell Jul 22 '19 at 02:23
  • Possible duplicate of [How do I create a dynamic key to be added to a JavaScript object variable](https://stackoverflow.com/questions/2462800/how-do-i-create-a-dynamic-key-to-be-added-to-a-javascript-object-variable) – John Ruddell Jul 22 '19 at 02:28

1 Answers1

1

You need to use [] notation when you want to access property using variable,

{buttonSet.map(function(button, i) {
  let pleaseHelpMe = button + `${i}`;
  return (
    <TouchableHighlight
    style={[styles.abacusButton, styles[pleaseHelpMe]]}
    ...
    >
      <Text>X</Text>
    </TouchableHighlight>
  );
})}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Oh. My. God. would you believe I've been trying to figure this out for 3 hours? Thank you kind sir. Will accept answer when the five minute time limit is up – JMcFar Jul 22 '19 at 02:25