I am learning React JS and trying to implement basic login button and text according to login status, button text is getting changed but the welcome text is not being changed (this is importing from another file). see my code below.
LoginControl.js
import React from 'react';
import Greeting from './Greeting';
function LoginButton(props) {
return <button onClick={props.onClick}>Login</button>;
}
function LogoutButton(props) {
return <button onClick={props.onClick}>Logout</button>;
}
class LoginControl extends React.Component {
constructor(props) {
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = {isLoggedIn: false};
}
handleLoginClick() {
this.setState({isLoggedIn: true});
}
handleLogoutClick() {
this.setState({isLoggedIn: false});
}
render() {
const isLoggedIn = this.state.isLoggedIn;
let button = null;
if(isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
}
}
export default LoginControl;
Greeting.js
import React, { Component } from 'react';
function UserGreeting() {
return <h1>Welcome back!</h1>;
}
function GuestGreeting() {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedin;
if(isLoggedIn) {
return <UserGreeting />;
} else {
return <GuestGreeting />;
}
}
export default Greeting;
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import LoginControl from './LoginControl';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<section>
<LoginControl />
</section>
</div>
);
}
}
export default App;
Is this happening because I am using same const isLoggedIn in both 2 files
isLoggedInbut you are trying to evaluate the variableisLoggedinwhich fails and thus gives youfalseto your local variable. Just fix your typo and it will work.