user14925601
user14925601

Reputation:

Issues with conditional rendering

I recently started learning react and just for practice purpose I am trying to make a login and logout thing, here i am trying to use conditional rendering where I stored my isLoggedIn to a state and I add a h1 for displaying the info whether the user is logged in or not and a button to toggle between login and logout

I add a onClick event to a button and changed the state whenever the button is clicked, but somehow it is not working without giving me error, here is my code:

class App extends React.Component{
    
    constructor(){
        super()
        this.state = {
            isLoggedIn: false
        }
        this.handleClick = this.handleClick.bind(this)
    }
    
    handleClick(){
        return(
            this.setState((prevState) => {
                isLoggedIn: !prevState.isLoggedIn
            })
        )
    }
    
    
    render(){
        return(
            <div>
                <h1>You Logged {this.state.isLoggedIn ? "In" : "Out"}</h1>
                <button style={{cursor:" pointer"}} onClick={this.handleClick}>Login {this.state.isLoggedIn ? "Out": "In"}</button>
            </div>
        )
    }
}

Upvotes: 0

Views: 132

Answers (1)

David
David

Reputation: 218808

This isn't doing what you expect:

this.setState((prevState) => {
    isLoggedIn: !prevState.isLoggedIn
})

In this syntax the curly braces are denoting a function, not an object. Since that function isn't returning anything, the state is being set to nothing.

(Additionally, what that function does is unintuitive but still technically valid. It's creating a label rather than assigning a value.)

Wrap the curly braces to make them an object being returned by the function:

this.setState((prevState) => ({
    isLoggedIn: !prevState.isLoggedIn
}))

Or explicitly define the return in the function:

this.setState((prevState) => {
    return {
        isLoggedIn: !prevState.isLoggedIn
    };
})

Generally the rule with the inline arrow functions is that if the very first token is an open curly brace then that is opening the function body. If the very first token is not an open curly brace then that is the start of an operation that produces the return value.


As an aside, the return in the click handler itself is superfluous in this case. Overall the handler function should just be:

handleClick(){
    this.setState((prevState) => ({
        isLoggedIn: !prevState.isLoggedIn
    }));
}

Upvotes: 3

Related Questions