Warning: setState(…): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state

When i ran my ReactJs script, I got the waring message “Warning: setState(…): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.” many times displayed in my console window. After analyzing my script i did some state changes inside the render() function. when i removed that state changes and put it as a variable my script was working fine wthout any warning message.

const ContentBlockComponent = React.createClass({
	displayName:"ContentBlock",
	getInitialState:function(){
		return{setActiveClass:this.props.action=='open' ? 'activeContent' : 'hideContent'}
	},
	render: function(){
		this.setState({setActiveClass:this.props.action=='open' ? 'activeContent' : 'hideContent'});
		return (
			<div className={"container "+ this.state.setActiveClass }>
				/..../
			</div>
		)
	}
});

When you are change the state value inside the render function then this warning will occur many times in console window.

Then i changed my script like

const ContentBlockComponent = React.createClass({
	displayName:"ContentBlock",
	render: function(){
		var setActiveClass = this.props.action=='open' ? 'activeContent' : 'hideContent';
		return (
			<div className={"container "+ setActiveClass }>
				/..../
			</div>
		)
	}
});

Leave a Reply

Your email address will not be published. Required fields are marked *