Conditional Rendering in ReactJs for one part in Html

Viewed 1651

I want to render some part of Html only if one of the variable is true. I have seen examples where I can return the whole element but I only want a if condition on one part of the html. I only want to show with 10 lines if one of the variables is true but html with 500 lines is common. Can I do that in return function?


const getCustomers= (props) => {
useEffect(() =>{ do something...});

 return (
<>
if(test === true){
<div> 10 lines</div>
else
{
do not show this div
}
}

<div> 500 lines</div> // Common
</>

)
};
4 Answers

Conditional rendering is only supported using ternary operator and logical and operator:

{
  something ? '10 lines' : '500 lines'
}

{
  something && '10 lines' || '500 lines'
}

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

For further details, you may read this, and the docs

Try to avoid logic inside of your return statements.

You can assign your conditional output to a JSX value, and always render it.

const Customers = () => {

  const optionalDiv = test === true && <div>10 lines</div>;

  return (
    <>
      {optionalDiv}
      <div>500 lines</div>
    </>
  );
};

you can use conditional (ternary) operator

return (
 <>
  { test === true ? (<div> 10 lines</div>) : null }
  <div> 500 lines</div>
 </>

)

I think just doing it like this should do it -

return (
    <>
        {test? <div> 10 lines</div> : null}
        <div> 500 lines which are common</div> 
    </>
);
Related