4

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?

2
  • You're using a local state to keep the current number, which is fine, until you want to access it from other component of the App. You may need redux to persist them in a global state. Commented Oct 23, 2016 at 10:15
  • What you have there isn't array at all but a multidimensional object. This is worth noting in case you are expecting array-like behaviours and methods to exist on it (like push, map, etc.) Commented Oct 23, 2016 at 10:46

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

-1
const DATA = [
  {
    'title': 'Test Series (12,13)',price:"1000",
  }, 
];

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.