Published on

How to Render React Component based on condition

Authors

Here's a little snippet on how to do it

// Based on https://github.com/romac/react-if
import React, { PropTypes } from 'react';

function render(props) {
  if (typeof props.children === 'function') {
    return props.children();
  }

  return props.children || null;
}

export function Then(props) {
  return render(props);
}

export function Else(props) {
  return render(props);
}

export function If(props) {
  const { children } = props;
  return (
    [].concat(children).find(c => (c.type !== Else) ^ !props.condition) || null
  );
}

If.propTypes = {
  condition: PropTypes.bool.isRequired,
  children: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.string,
    PropTypes.number,
    PropTypes.object,
  ]),
};
export default If;

import {If} from 'components/RenderIf'
export const Header = (props) => (

   <div>
     <if condition={props.authenticated}>
       <link to="/logout" class="btn btn-outline-danger pull-right">Logout
     </if>
   </div>
  )