简体   繁体   中英

How to render jsx with conditions using react?

i want to render jsx based on condition using react.

what i am trying to do?

if items.length <= 0 and shared_items.length <= 0 i want to display some content.

if items.length > 0 or shared_items.length > 0 i want to display other content.

below is my code,

function Parent() {
    return(
        {items.length <= 0 && shared_items.length <= 0 && 
            <div>
                <span> first</span>
            </div>
        }
        {items.length > 0 or shared_items.length > 0 && //unreachable code here
            <div>
                <Button> click</Button>
                <span> second </span>
            </div>
        }
    );
}

the second condition code is unreachable. not sure how to render jsx based on condition.

could someone help me fix this. thanks.

The or operator is wrong.

function Parent() {
    return(
        {items.length <= 0 && shared_items.length <= 0 && 
            <div>
                <span> first</span>
            </div>
        }
        {(items.length > 0 || shared_items.length > 0) && //unreachable code here
            <div>
                <Button> click</Button>
                <span> second </span>
            </div>
        }
    );
}

In order to simplify your code, you can also assign your condition to a boolean variable

function Parent() {
    const conditionA = items.length <= 0 && shared_items.length <= 0  ? true : false;
    const conditionB = items.length > 0 || shared_items.length > 0 ? true: false;
    return(
        {conditionA && 
            <div>
                <span> first</span>
            </div>
        }
        {conditionB && //unreachable code here
            <div>
                <Button> click</Button>
                <span> second </span>
            </div>
        }
    );
}

You can also create this component for conditional render in react .

export default function App() {
  const items = [1, 2, 3, 4, 5];
  const shared_items = [3, 4, 5];

  const RenderFunc = () => {
    if (items.length <= 0 && shared_items.length <= 0) {
      return (
        <div>
          <span> first</span>
        </div>
      );
    }
    if (items.length > 0 || shared_items.length > 0) {
      return (
        <div>
          <button> click</button>
          <span> second </span>
        </div>
      );
    }
  };

  return (
    <div>
      <RenderFunc />
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM