Babs Babs - 12 days ago 6
React JSX Question

show image if stored date is not current date

I have two images and got to display one of them every alternate day.
I'm using http://momentjs.com/ and checking if the storedDate = currentDate as per below code. However, I see that the state of the storeDate is not getting updated.
Could anyone shed some light here?

getInitialState() {
storedDate: ''
}

onDateChanged(currentDate) {
this.setState({ storedDate: currentDate });
},

render(){
var currentDate = moment();
var displayImage;
if (currentDate.isSame(this.state.storedDate, 'day')) {
displayImage = Image1;
this.onDateChanged(currentDate);
} else {
displayImage = Image2;
}
}

Answer

The render function is suppose to be pure function, i.e it should not change the state.

React re-renders every time a state is changed, thus setState in a render functions throws into a infinite loop of rendering.

More here: https://facebook.github.io/react/docs/react-component.html#render

Update the state even before the component is mounted using componentWillMount() life cycle method

Read more : https://facebook.github.io/react/docs/react-component.html#componentwillmount

This SO answers may give more insight:ReactJS - Does render get called any time "setState" is called?

Comments