DEV Community

Discussion on: How to write if statement in React.js?

simondell profile image
Simon Dell

You can have further fun with this.

// When.jsx
export default ({ children, condition }) => {
    const shouldRender = typeof condition === 'function'
        ? condtion()
        : !!condition

    if(!shouldRender) return null

    return children

// Consumer.jsx
import When from '../components/When'

export default (props) =>
    <When condition={props.whateverYouLike}>
        <p>Hello, world!</p>
Enter fullscreen mode Exit fullscreen mode

Something like this makes for a comfortable reading experience when you have complex conditions, or many children. At first glance, it seems like a JSX syntax of the separate render function approach.

You can also wrap <When> in a higher-order component to do things like conditionally rendering based on something in Redux state. It's pretty common to have multiple parts of a page change in quite different ways if the user is logged in. <When> lets you abstract that behind a really simple interface. It's also fun to read.

If you wanted to go wild, you could make a <Switch> that inspects all the conditions of its <When> children, only rendering one. That's the essence of what React Router does.