Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing React button text upon Login/Logout

Tags:

I'm fairly new to React and am working on making an app that involves a sign in/login. I have my login button on my nav bar and I wish to change the text so that when the user logs in the text of the button changes to "Loggout" and vice versa.

class SiteBar extends React.Component {
constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
        isOpen: false,


    };
}
toggle() {
    this.setState({
        isOpen: !this.state.isOpen,
    });
}
render() {
    return (
        <div>
        <div>
            <Navbar color="faded"  light expand="md">
                <Collapse isOpen={this.state.isOpen} navbar>
                    <Nav className="ml-auto" navbar>
                        <NavItem>
                            <Button color="light" onClick={() => this.props.clickLogout()}>{this.onClick ? 'Login' : 'Logout'}</Button>
                        </NavItem>
                    </Nav>
                </Collapse>
            </Navbar>
        </div>

Keeping in mind I am passing a function to my main app file, any advice is welcome. Thanks in advance.

like image 210
ASummers Avatar asked Feb 25 '18 01:02

ASummers


1 Answers

You should add a state to the class where you defined this.props.clickLogout

this.state = {
    isLoggedIn: false
}

Then, you also pass the props from that class and pass the state as a prop.

<SiteBar clickLogOut={this.clickLogOut} isLoggedIn={this.state.isLoggedIn}/> 

The condition for the text of the button would be the prop isLoggedIn. When the button fires the onClick function, the function clickLogout() should change the isLoggedIn to true, thus re-rendering ClassSite and the button with the text Logout

<Button color="light" onClick={() => this.props.clickLogout()}>
    {this.props.isLoggedIn? 'Logout' : 'Login'}
</Button>
like image 60
Leomar Amiel Avatar answered Sep 23 '22 12:09

Leomar Amiel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!