How to Render React Component based on condition

May 04, 2017

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>
  )

👋 I'm Ashik Nesin • Sr. Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP