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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With