0

I'm trying create-react-native-app for the first time and I want to change text on varying time intervals. But my code only gives me the last item of the array.

import React from 'react';
import { Text } from 'react-native';

const blinkText = [
  {
    text: "A",
    time: 500,
  },
  {
    text: "B",
    time: 1000,
  },
  {
    text: "C",
    time: 1000,
  },
  ];


export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {};
  }

  componentDidMount() {
    this.interval = setInterval(() => {
      blinkText.map(value => this.setState(value))
    }, this.state.time);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }


  render() {
   return(
    <Text>{this.state.text}</Text>
    );
  }

}

I know I have my problem at componentDidMount() but I could not think of a way. Please take a look at my code and modify. Thanks.

user8703143
  • 173
  • 1
  • 14

1 Answers1

0

Try this

componentDidMount(){
    blinkText.map(e => {
        setTimeout(() => {
            this.setState(
                prevState => ({
                    text: [...prevState.text, e]
                });
            );
        }, e.time);
    });
}

Note that, this.stat.text is an array, so you should render it inside your render() method by applying map()

Example:

{ this.state.text.map((e, i) => {
   return (
     <Text key={i}>{e}</Text>
   );
})}
Singh
  • 1,887
  • 3
  • 18
  • 29