React | State Toggling
if you are wondering How to toggle Boolean state in react component, then maybe this little code snippet for you...
Ingredients :
HTMLCSS- React ***
Dependency :
- Bootstrap (Only for button)
command: npm start
import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
const App = () => {
const [isLoggedIn, setIsLoggedIn] = useState(true);
//let isLoggedIn = true; <<<|<<< this approach not work...
// Element Variable
const buttonText = isLoggedIn ? 'Log Out' : 'Log In';
const classNameChange = isLoggedIn ? 'danger' : 'success'
const toggleFunction = () => {
//isLoggedIn = !isLoggedIn; <<<|<<< this approach not work...
setIsLoggedIn(!isLoggedIn);
}
const style = {
textAlign: 'center',
marginTop: '20px',
lineHeight: 5
};
return (
<div style={style}>
{
// Ternary Conditional Operator
// Conditionally UI or HTML rendering...
isLoggedIn ? <h1>Welcome</h1> : <h1>Good By</h1>
}
<button onClick={toggleFunction} className={'btn btn-' + classNameChange}>
{buttonText}
</button>
</div>
);
};
export default App;
Comments
Post a Comment