Home > Mobile >  react classname 3 conditional rendering hide with display none
react classname 3 conditional rendering hide with display none

Time:07-05

I have 3 variables that I must evaluate to hide a div if a condition is met between these 3 variables, something like this:

appState.fullResults
appState.someResults
appState.otherResults

So, when appState.fullResults and appState.someResults come empty, but appState.otherResults has something, I need to hide a div, this code snippet is an example:

<div classname='container'>
<div classname='full-some'>
boxes
</div>
<divclassname='others'>
boxes
</div>
</div>

I try something like this, but dont work

className={`${
                        (!appState.someResults?.length > 0 && otherResults?.length > 0)
                          ? 'container-boxcard'
                          : 'd-none'
                      }`}

I always get the same result: if othersResults brings something and someResults brings nothing, the "d-none" is not passed to hide it

https://imgur.com/bZBUGo9 Still evaluates false and applies the d-none class

Hope I have explained well, thank you for your help.

CodePudding user response:

Try this :

const { fullResults, someResults, otherResults } = appState;
const className = !fullResults?.length && !someResults?.length
&& otherResults?.length ? 'd-none' : 'container-boxcard';
<YourComponent className={className} {...props} />

CodePudding user response:

!appState.someResults?.length > 0 is hard to understand, I'd suggest you should change it to !appState.someResults?.length or appState.someResults?.length === 0 (you can choose one of them).

I haven't seen you declared otherResults anywhere else, so I'd assume that otherResults?.length > 0 should be appState.otherResults?.length (or appState.otherResults?.length > 0).

className={`${(!appState.someResults?.length && appState.otherResults?.length)
               ? 'd-none'
               : 'container-boxcard'
}`}

when appState.fullResults and appState.someResults come empty, but appState.otherResults has something

According to your demonstration, you can follow this with 3 conditions

className={`${(!appState.someResults?.length && !appState.fullResults?.length && appState.otherResults?.length)
               ? 'd-none'
               : 'container-boxcard'
}`}
  • Related