@straw-hat/react-when

When React Component for conditional rendering

Usage no npm install needed!

<script type="module">
  import strawHatReactWhen from 'https://cdn.skypack.dev/@straw-hat/react-when';
</script>

README

@straw-hat/react-when

When React Component for conditional rendering.

Usage

import { When, Unless } from '@straw-hat/react-when';
import { ReallyExpensiveComponent } from './really-expensive-component';

function App({ title, hasX }) {
  function lazyCalculation() {
    // do some expensive stuff here, or safe some executing cycles
    // (measure before taking decisions)
    return true;
  }

  return (
    <div>
      <h2>{title}</h2>

      {/* When component takes a children-function */}
      <When value={hasX}>
        {()=> <ReallyExpensiveComponent/>}
      </When>

      <When value={hasX}>
        {()=> (
          <div>

            {/*
              When component takes functions as the value in case you do not
              waste computation calculating the value, unless it is necessary.
              Notice that this When would not render unless the previous one
              renders first, therefore, the value is not calculated until then.
            */}
            <When value={lazyCalculation}>
              {()=> <ReallyExpensiveComponent/>}
            </When>

          </div>
        )}
      </When>

      {/* Or you could use Unless which is the opposite to When */}
      <Unless value={hasX}>
        {()=> (
          <p>It does not has X</p>
        )}
      </Unless>
    </div>
  );
}