Hey. I've tried to create what you said. But I get an error. How can I call timer() inside componentDidMount? This whole code might be wrong. So I would be glad if you could help. :)
export default class About extends React.Component {
constructor(props) {
super(props);
this.state = {
arr: this.props.language.about.style[0]
};
}
timer() {
let i = 0;
function createTimer() {
this.setState({
arr: this.props.language.about.style[i]
});
i++;
if (i === this.props.language.about.style.length) {
i = 0;
}
}
setInterval(createTimer, 500);
}
componentDidMount() {
timer();
}
render() {
return (
<div>{this.state.arr}</div>
);
}
}
That's how I've done it during React learning from official docs. You can see it live here: react-play-neone.herokuapp.com
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000); }
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<FormattedDate date={this.state.date} />
</div>
);
}
}
Here is more info about arrow functions introduced in es6 es6-features.org
That’s not totally wrong. Try separate things. Create a function that only handles what should happen, when the timer hits. Nothing about what you want to see, just the pure change that causes later the Ui change
My kids will be in bed in about 2 hours so there’s a little time left.
Sebastian With this I get the error: TypeError: Cannot read property 'language' of undefined after 1 second. this.props.language is working in the constructor. But not in timer. Idk what's wrong. Let's see what you get in 2h+/-. ;)
export default class About extends React.Component {
constructor(props) {
super(props);
this.state = {
arr: this.props.language.about.style[0]
};
this.timer = this.timer.bind(this);
}
timer() {
let i = 0;
setInterval( function() {
this.setState({
arr: this.props.language.about.style[i]
});
i++;
if (i === this.props.language.about.style.length) {
i = 0;
}
}, 1000);
}
componentDidMount() {
this.timer();
}
render() {
return (
<div>{this.state.arr}</div>
);
}
}
Sebastian
Here is my take.
codesandbox.io/s/8lwppxjy19
Thanks to Artur Maslov , I almost forgot to cleanup (componentWillUnmount) :)
It's pretty similar to other answers here. In case you're wondering.. I guessed you want to iterate through names on the about page so I put up some names. They are passed in via props in the index.js.