Reputation:
I have a react component and have a condition on it.
I want to have a different return jsx depending on the condition result.
This is what I've got but it's only returning the last one.
Here's the code:
import React, { Component } from 'react';
import { Redirect } from 'react-router';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: sessionStorage.getItem('isLoggedIn'),
redirect: false,
};
}
render() {
if (!this.state.isLoggedIn) {
return (
<div>
<h1>You are NOT logged in</h1>
</div>
);
} else {
return (
<div>
<h1>You ARE logged in</h1>);
</div>
}
}
}
export default Login;
How can I fix this?
Upvotes: 0
Views: 84
Reputation: 3248
Assuming, false is saved in sessionStorage corresponding to isLoggedIn
You should use:
this.state = {
isLoggedIn: sessionStorage.getItem('isLoggedIn') === 'true',
redirect: false,
}
values stored in sessionStorage are string. So, false will be stored as 'false'. So, this.state.isLoggedIn is always true.
Upvotes: 2
Reputation: 2216
You have a closing bracket in the wrong place, for one. It should be after div
and not h1
. BTW, There is no need for the 2nd return.
render() {
return (
<div>
<h1>You are { (!this.state.isLoggedIn) ? 'NOT' : '' } logged in</h1>
</div>
);
}
Upvotes: 1