React Native pass parameters through map function
In both cases you are unnecessarily wrapping item
in {}. For both of these lines, the expressions inside the outer {} are pure javascript (an array and a function) and should follow javascript syntax.
So the lines should read as follows:
style={[styles.button, (this.state.location===item && styles.buttonPressed)]}
and
onPress={()=>this.buttonPress(item)}
nwilliams36
Updated on July 20, 2022Comments
-
nwilliams36 almost 2 years
I am just learning React Native and I want to create a series of buttons using dynamic data. My current code is:
var locations = this.state.campus.map(function(item, key){ return( <TouchableHighlight key={key} style={[styles.button, (this.state.location==={item} && styles.buttonPressed)]} underlayColor='#dddddd' onPress={()=>this.buttonPress({item})} > <Text style={ styles.plainText}>{item}</Text> </TouchableHighlight> )
My issue is with the lines
style={[styles.button, (this.state.location==={item} && styles.buttonPressed)]}
and
onPress={()=>this.buttonPress({item})}
I am trying generate these lines using the data dynamically off the map function. These lines of code work perfectly if I use static data (ie generate each button separately), but fail using dynamic data. The code does produce a display so the issue is not with rendering, the issue is with the functionality.
With the button press I get the error message undefined in not an object while the style simply causes the whole display not to render.
It is obvious that the dynamic data ({item}) works inside the Text element but not when passed to the other two elements as data. I have tried using {{item}} but this throws a syntax error.
Is there a way to handle dynamic data like this in React Native?
-
nwilliams36 almost 9 yearsYou are probably correct, however this does not solve the issue, it just creates more errors. I now think my whole design is wrong so I will go back to the drawing board and work out how to do this a different way. I think I need to create these buttons in a ListView.
-
Enamul Hassan almost 8 yearsWelcome to Stack Overflow! This is really a comment, not an answer. With a bit more rep, you will be able to post comments.
-
Sunny Patel over 7 yearsCould you provide an example of where to create this variable?
-
hippietrail over 6 yearsYou should always avoid using either
bind
or arrow functions inside JSX/inside therender
function because they create a new function every time which causes every item in the list/array/map to be re-rendered when a single one is pressed unless you also provide a custom comparison function inshouldComponentUpdate
that skips comparing thebuttonPress
field. -
hippietrail over 6 years