How can I go about changing a boolean value after conditionally rendering something in react?
I want to make a conditional render in React and afterwards change the value of a boolean used in the condition, but have no idea on how you do it. It's something simple that is useful so i suspect it is possible somehow, but have no idea about the correct syntax/method and my google search results are filled with irrelevant stuff.
let hasBeenPrinted = false
return(
{deals.map((deal) => (
deal.value>10000 && !hasBeenPrinted && <h4>Congratulations on your first big deal</h4>
<Deal deal={deal} />
)
)
So what I want to do here is to change the value of hasBeenPrinted to true so that the congratulations text will only be printed once.
CodePudding user response:
You can use deals.map((deal, index)=>{ ... }) and check if the index is 0 to print congratulations only the first time. Changes reflected in your code would be as such.
return(
{deals.map((deal,index) => (
deal.value>10000 && index == 0 && <h4>Congratulations on your first big deal</h4>
<Deal deal={deal} />
)
)
CodePudding user response:
If I understand you correctly, deals is an array that can have multiple "big deals" (deal.value > 10000). However, you want to make sure that "congratulations..." is printed at most 1 time even if there are, say, 7 big deals in deals?
If that's correct, it sounds you would be better off filtering deals like so
const hasBigDeal = deals.some( deal => deal.value > 1e4)
and then conditionally rendering the <h4 /> based on hasBigDeal. I don't believe updating react state or a local variable such as hasBeenPrinted is appropriate here as the information you care about already exists before the render (return) statement.
Your final code would look like this:
const hasBigDeal = deals.some(deal => deal.value > 1e4);
return(
<>
{hasBigDeal && <h4>Congratulations on your first big deal</h4>}
{deals.map((deal) => <Deal deal={deal} />)}
</>
And in case you are not already aware, there are tons of super helpful methods exposed on the Array object in javascript that can make your life a ton easier. In my example above, I used Array.some (link to MDN docs here)
Also, the <>...</> is called a React Fragment which is also very useful if you haven't heard of them either (link to docs)
