React Conditional Rendering

Using if operator with props

function Heading(props) {
  const isHome = props.isHome;
  if (isHome) {
    return <HomeHeading />;
  }
  return <PageHeading />;
}

Using if operator with state

render() {
  const isHome = this.state.isHome;
  let heading = null;
  if (isHome) {
    heading = <HomeHeading />;
  } else {
    heading = <PageHeading />;
  }

  return (
    <div>
      {heading}
    </div>
  );
}

Using ternary operator

<div>
  {isHome ? <HomeHeading /> : <PageHeading />}
</div>

Using logical operator

<div>
  {messages.length > 0 &&
    <h1>
      You have messages
    </h1>
  }
</div>

Prevent component from rendering

function Modal(props) {
  if (!props.isShow) {
    return null;
  }

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

Leave a Reply

Your email address will not be published. Required fields are marked *