1.0.0 • Published 6 years ago

react-cond-disp v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
6 years ago

react-cond-disp

This small module allows you to write conditional render statements in cleaner way.

Installation

npm

$ npm i -s react-cond-disp

yarn

$ yarn add react-cond-disp

Usage

react-cond-disp can take up to 3 props:

  • condition - a boolean, when the condition is true, a children is rendered;
  • children - React component or string, required;
  • fallback - when the condition evaluates to false, this component is rendered, React component or string, not required, defaults to null.
import React from "react";
import ConditionalDisplay from "react-cond-disp";
import canAccess from "canUserAccessResource.js";
import hasTokenExpired from "hasTokenExpired.js";

class SecretKey extends React.Component {
  render() {
    return (
      <ConditionalDisplay
        condition={
          canAccess("secretKey", this.props.userRoles) &&
          !hasTokenExpired(this.props.token)
        }
        fallback={<div>You cannot access secret key</div>}
      >
        <h2>{this.props.secretKey}</h2>
      </ConditionalDisplay>
    );
  }
}

Alternatively, this component would look like this:

import React from "react";
import canAccess from "canUserAccessResource.js";
import hasTokenExpired from "hasTokenExpired.js";

class SecretKey extends React.Component {
  render() {
    return canAccess("secretKey", this.props.userRoles) &&
      !hasTokenExpired(this.props.token) ? (
      <h2>{this.props.secretKey}</h2>
    ) : (
      <div>You cannot access secret key</div>
    );
  }
}