Home > database >  Generate touchable oppacity with map using nested array
Generate touchable oppacity with map using nested array

Time:11-14

I write a calculator app and i need to generate touchable opacity using map I have a nested array

state= {
  buttons:[' ', '-', '*', '/', 'Del']
}

And I generate touchable opacity using map

    <View style={styles.container}>
      <View style={styles.second_con}>
   {
      this.state.buttons.map((item,index)=>{
        return(
        <TouchableOpacity style={styles.buttons} key={index}>
              <Text>{item}</Text>
            </TouchableOpacity>
        )   
      }
    ) 
   }   
    </View>     
  </View>

And it works How can i generate it using nested array ?

buttons1:[['√', ' ', 'x!', ' /-', '%'],
      ['e^x', '10^x', 1, 2, 3],
      ['ln', 'log', 4, 5, 6],
      ['e', '^2', 7, 8, 9],
      ['π', '^3', ',', 0, '='],
           ]

CodePudding user response:

You need to flatten the list. You can do this with the function below

const flattenLst = (lst)=>{
  let res = []
  lst.forEach(curSet=>{
      res = [...res,...curSet] // TODO: read into spread operators in javascript
  })

  return res;
}

Then do

   <View style={styles.container}>
      <View style={styles.second_con}>
   {
      // flatten this.state.buttons
      flattenLst(this.state.buttons).map((item,index)=>{
        return(
        <TouchableOpacity style={styles.buttons} key={index}>
              <Text>{item}</Text>
         </TouchableOpacity>
        )   
      }
    ) 
   }   
    </View>     
  </View>

CodePudding user response:

If you want to preserve the rows you have laid out in your nested array, map through the rows, and use your existing map for each row. Here's an example:

<View style={styles.container}>
  <View style={styles.second_con}>

  {
    this.state.buttons1.map(row => (
      <View style={style.row_con}>

      {
        row.map((item, index) => (
          <TouchableOpacity style={styles.buttons} key={index}>
            <Text>{item}</Text>
          </TouchableOpacity>
        ))
      }

      </View>
    ))
  }  

  </View>     
</View>
  • Related