3

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 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>
    </>
  );
};

1 Comment

I would do the same way... Best solution from my view.
0

you can use conditional (ternary) operator

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

)

Comments

0

I think just doing it like this should do it -

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.