Skip to content
Today's Tech Byte: Configuration concerns with elements as props

Today's Tech Byte: Configuration concerns with elements as props

Posted on:October 25, 2023

In the previous chapter, we saw how we can use the children prop to improve performance. But in reality, we can use this pattern to solve other problems as well.

Configuration concerns

I’m sure you’ve seen “children as props” pattern used to address configuration concerns several times, but you might not have known what it was called (or you knew because you are better than me).

Let’s take this package for example react-native-bottom-sheet.

In order to use this package, you need to wrap your content with the BottomSheetModal component. In other words, I’m asked to provide the content and ‘BottomSheetModal’ will take care of putting it in the right place.

const App = () => {
  // ref
  const bottomSheetModalRef = useRef < BottomSheetModal > null;

  // variables
  const snapPoints = useMemo(() => ["25%", "50%"], []);

  // callbacks
  const handlePresentModalPress = useCallback(() => {
    bottomSheetModalRef.current?.present();
  }, []);
  const handleSheetChanges = useCallback((index: number) => {
    console.log("handleSheetChanges", index);
  }, []);
  return;
  <BottomSheetModal
    ref={bottomSheetModalRef}
    index={1}
    snapPoints={snapPoints}
    onChange={handleSheetChanges}
  >
    <Content />
  </BottomSheetModal>;
};

Default values for the elements from props

Let assume the the creator of this package wanted to force some kind of default props? How would you do that?

Here where React.cloneElement comes to the rescue. cloneElement is a function used to clone an element and pass it new props.

const BottomSheetModal = ({ children }) => {
  const defaultProps = {
    position: "absolute",
  };
  // clone children and assign new props to it
  const clonedIcon = React.cloneElement(children, defaultProps);

  return;
  <Modal
    ref={bottomSheetModalRef}
    index={1}
    snapPoints={snapPoints}
    onChange={handleSheetChanges}
  >
    {children}
  </Modal>;
};

So next time, you face a similar problem, you know what to do, hopefully.

If you have any suggestions or questions, feel free to reach out to me on Twitter or LinkedIn.

P.S. this post is inspired by the book, but it’s not a summary of it. I’m just sharing what I learned from it. If you want to learn more about React, I highly recommend you to read it.