I have this code:
constructor(props) { super(props) this.state = { loginButton: '', benchmarkList: '' } if (props.username == null) { this.state.loginButton = <GoogleButton></GoogleButton> } else { } }
It is giving me an ESLint warning:
Do not mutate state directly. Use setState() react/no-direct-mutation-state.
Now what am I supposed to do as I can’t use setState
inside constructor
directly as it creates error and updating like this gives me error.
Advertisement
Answer
First of all, we should not store the ui components inside state variable, state should contain only data. All the ui part should be inside render
method.
If you want to render
some component on the basis of any data then use conditional rendering. Check the value of this.state.loginButton
and if it is null
then render that button.
Like this:
constructor(props) { super(props) this.state = { loginButton: props.username, benchmarkList: '' } } render(){ return( <div> {!this.state.loginButton ? <GoogleButton></GoogleButton> : null} </div> ) }
Ideally we should not store the props
value in state
also, so directly use this.props.username
, i did that because don’t know about the complete code.