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?
In React, the map() function is most commonly used for rendering a list of data to the DOM. To use the map() function, attach it to an array you want to iterate over. The map() function expects a callback as the argument and executes it once for each element in the array.
Keys should be given to the elements inside the array to give the elements a stable identity: const numbers = [1, 2, 3, 4, 5]; const listItems = numbers.map((number) => <li key={number.toString()}> {number} </li> ); The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.
I suggest breaking this into two components. The CommentList and the Comment component. class Comment extends Component { constructor(props){ super(props); this. state = { isReply: false } } changeIsReply = () => { this.
The answer is, you use Array. map() in your component and return JSX elements inside the Array. map() callback function to render the UI.
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)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With