How to prevent HOC from rendering if wrapped component renders nothing

Viewed 32

I have components that can return null in render based on their props. Props are not the same between components. Now I want all of my components to render a fancy divider after them. I decide to use one shared HOC for this (e.g. by importing said HOC in my components and exporting the new wrapped component).

However, now I end up in a situation where if my actual components render nothing I still get the divider rendered from the HOC and my page only contains lonely dividers. In this case I would want the HOC to render nothing. Can I solve this in the HOC? I could check different props before rendering the HOC+wrapped component but that would have to be done everywhere. If not HOC, is there some other way of solving this?

import React from 'react'
import ReactDOM from 'react-dom'

const withDivider = (Component) => {
  return ({ fancyDividerProp, ...props }) => (
    <>
      <Component {...props} />
      <hr some-fancy-prop={fancyDividerProp} />
    </>
  )
}

const SpicyComponent = ({isSpicy}) => {
  if (!isSpicy) return null
  return (
    <p>Spicy!</p>
  )
}
const SpicyWithDivider = withDivider(SpicyComponent)


const SweetAndSourComponent = ({isSweet, isSour}) => {
  if (!isSweet || !isSour) return null
  return (
    <p>Sweet&Sour!</p>
  )
}
const SweetAndSourWithDivider = withDivider(SweetAndSourComponent)


class App extends React.Component {
  render() {
    return (
      <div>
        <SpicyWithDivider isSpicy={false} />
        <SweetAndSourWithDivider isSweet={true} isSour={false} />
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
)
0 Answers
Related