DEV Community

Adrian Rolloque
Adrian Rolloque

Posted on

Render Props in a React Functional Components

I think render props is a little more straightforward to implement in Functional Components compared to the class components.

One example that I have here is the the OutsideClickObserver.jsx HOC that I created to observe outside click of from the wrapper div.

/**
 * Component that alerts if you click outside of it
 */
 export default function OutsideClickObs(props) {
  const wrapperRef = useRef(null);
  //Take note to use a function keyword as the shorthand does not work as expected ( error: is not a function)
  useOutsideClickObserver(wrapperRef, (clickedOutside, result)=>{
    if(clickedOutside){
      props.outsideClickHandler();
    }else{
      //nothing here.
    }
  });

  return <div ref={wrapperRef}>{props.children}</div>;
}
Enter fullscreen mode Exit fullscreen mode

In this example we are using props.children, which is fine actually.
However if we want to achieve similar results compared to the example given in React documentation, then all we have to do is to pass a props.component to our HOC and render that instead of the props.children.

Top comments (1)

Collapse
 
adzz profile image
Adrian Rolloque

Actually, rendering the props.children makes the same point.