Boolean in state in React
Let's make a state inCart
, which will show whether the product is in the cart or not:
function App() {
const [inCart, setInCart] = useState(false);
return <div>
</div>;
}
Let the value false
mean that the product is not in the cart, and the value true
mean that it is in the cart. Let's output this information using the ternary operator:
function App() {
const [inCart, setInCart] = useState(false);
return <div>
<span>{inCart ? 'in the basket' : 'not in the basket'}</span>
</div>;
}
Now let's make a button that, when clicked, will add the product to the cart:
function App() {
const [inCart, setInCart] = useState(false);
return <div>
<span>{inCart ? 'in the basket' : 'not in the basket'}</span>
<button onClick={() => setInCart(true)}>btn</button>
</div>;
}
Let's modify our code so that the first click on the button adds to the cart, and the second one removes from it:
function App() {
const [inCart, setInCart] = useState(false);
return <div>
<span>{inCart ? 'in the basket' : 'not in the basket'}</span>
<button onClick={() => setInCart(!inCart)}>btn</button>
</div>;
}
Make a button that when clicked will ban the user and a button that when clicked will unban the user.
Modify the previous task so that of the two buttons, only the corresponding one is always visible. That is, if the user is banned, the unban button is visible, and if not banned, the ban button is visible.