'Objects in React Native
I have a piece of text and every time you click on it the text changes to the next item in the object. I also need the name of the one saying the text so I used a multidimensional array like this:
let texts = {
0:{
"name" : "Bob",
"text" : "Hello, this is a text",
},
1:{
"name" : "Peter",
"text" : "Hey there.",
},
};
This is my state:
this.state = {
textNumber: 0,
};
And this is the function I call onPress:
nextScene = () => {
if(this.state.textNumber >= Object.keys(texts).length-1){
}
else{
this.setState({textNumber: this.state.textNumber+1})
}
};
It works perfectly just the way I want it. But my question is: is this the way it should be done in React Native? Or is there a better way?
Solution 1:[1]
You probably want an array of objects:
let texts = [
{
"name" : "Bob",
"text" : "Hello, this is a text",
},
{
"name" : "Peter",
"text" : "Hey there.",
},
];
Then you can do:
if(this.state.textNumber < this.state.texts.length-1) {
this.setState({textNumber: this.state.textNumber+1});
}
If you want a loop, you can also do the following:
this.setState({textNumber: this.state.textNumber+1 % this.state.texts.length});
About your question, there is no difference between doing this in React Native or not. This is merely JS.
It is fine to keep this in the state (both React or RN). If you want more fancy solution you can write a HOC to manage the state of your component (see for example recompose).
Solution 2:[2]
const DATA = [
{
'title': 'Test Series (12,13)',price:"1000",
},
];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ferran Negre |
| Solution 2 | General Grievance |
