It's very similar to this example in the React documentation. Save the index of the current message in state
, starting with 0, and then in componentDidMount
use setInterval
to call setState
to increment it (wrapping around if you want to do that, or stopping when you reach the end if you want to do that).
Also:
- Correct your
extends
clause: Component
should be capitalized.
- You should pass on the arguments to
constructor
to super
.
this.super()
shouldn't have this
on it.
Something like this (this one keeps going, instead of stopping):
const { Component } = React;
class Test extends Component {
constructor(...args) {
super(...args);
this.state = {
messages: [1, 2, 3, 4, 5],
index: 0
};
}
componentDidMount() {
this.timer = setInterval(() => {
this.setState(({messages, index}) => {
index = (index + 1) % messages.length;
return {
index
};
});
}, 3000); // 3000ms = three seconds
}
render() {
const { index, messages } = this.state;
return(
<p>{messages[index]}</p>
);
}
}
ReactDOM.render(
<Test />,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Re:
constructor(...args) {
super(...args);
// ...
}
You'll see people doing this instead a lot, and they do this in the React documentation as well:
constructor(props) {
super(props);
// ...
}
That only passes on the first argument. Early on I got in the habit of passing them all along, but I guess the React team probably won't add more arguments to the standard constructor call given how much code follows the example that only passes on the first...