Reputation: 99
I am just wondering on how can I avoid duplicating this code when I am conditionally rendering a component.
What I have so far is a navbar component that is connected to redux and it gets state of (isAuth or not) if it's it would render the div with the logout() else it would render the div with login().
Now this approach is not quite good and it's repetitive. I have come across this https://blog.hackages.io/conditionally-wrap-an-element-in-react-a8b9a47fab2 which basically allows you to conditionally render components without duplicating the code but Unfourtnely I was unable to get my head around it. Sorry, I am just learning to react at the moment.
If you please tell me how to use this or if there is an alternative way that i can try that would be very helpfull
Thanks
function Navbar({ isAuth, logOut }) {
if(isAuth) {
return(
<div className="navbar">
<a> link A</a>
<a> link B</a>
<a> link C</a>
<a> link D</a>
<button onClick={() => logOut()} > Logout </button>
</div>
)
}
return (
<div className="navbar">
<a> link A</a>
<a> link B</a>
<a> link C</a>
<a> link D</a>
<button> Login </button>
</div>
)
}
const mapStateToProps = ({ login }) => {
return {
isAuth: login.isAuthenticated
};
};
export default connect(
mapStateToProps,
{ logOut }
)(Navbar);
Upvotes: 0
Views: 427
Reputation: 2122
Just make the button render conditional;
function Navbar({ isAuth, logOut }) {
return(
<div className="navbar">
<a> link A</a>
<a> link B</a>
<a> link C</a>
<a> link D</a>
{isAuth ? <button onClick={() => logOut()} > Logout </button> : <button> Login </button>}
</div>);
}
}
const mapStateToProps = ({ login }) => {
return {
isAuth: login.isAuthenticated
};
};
export default connect(
mapStateToProps,
{ logOut }
)(Navbar);
You can place basic conditions within render/returns wrapped in curly braces - {}. Basically if isAuth is truthy render logout, otherwise login.
Upvotes: 4