I want to display a component depending on a variable. The variable should be able to hold a flexible amount of conditions/types.
Example: I want to display my component if test1 === false or test2 equals a number greater than 0. But also should allow to expand. Here is what I am trying so far.
const test1 = false
const test2 = 10
const conditionVar = test1 === false || test2 > 0
return (
{
conditionVar ? <MyComponent /> : null
}
)
Questions would be if this is good or bad practise? Can I extend this for example if I needed test3, test4... variables in the future as conditions? Will it be safe and run as expected every time?
CodePudding user response:
That's common practice when it's inside a larger JSX structure, although with your specific example there's no reason to be indirect, just:
return conditionVar ? <MyComponent /> : null;
If you know conditionVar
will be null
, undefined
, or false
(specifically) when you don't want to render or any truthy when you do, you can also do:
return conditionVar && <MyComponent />;
Or in a larger structure:
return <div>
{/*...something...*/}
{conditionVar && <MyComponent />}
</div>;
But another option is to just set a variable to the thing you want to render:
const component = !test1 || test2 > 0
? <MyComponent />
: null;
then when rendering, use component
:
return component;
or in a larger structure:
return <div>
{/*...something...*/}
{component}
</div>;
They're all fine in context.
CodePudding user response:
Like others have mentioned, you approach is fine. However, I would argue that in a more complex situation, it would be more readable to put the different conditions and renders one after another.
Also, you can utilise early returns so that if there is no data to display, your component will exit immediately.
Here's an example:
if (noData) {
return null;
}
if (condition1) {
return <Component1 />;
}
if (condition2) {
return (
<div>
<Component2A />
<Component2B />
...
</div>
);
}
Having this in mind, I would rewrite your example like this:
if (test1 && test2 <= 0) {
return null;
}
return <MyComponent />;
Note: test1
is not precisely the same as the negative of test1 === false
but i believe that's what the intention was.