Function as a Child By Example – Part 1
A practical approach to Function as Children in React
Function as a Child components are React components that expect their children to be a function that returns more React components. The component will run the given function with some custom data passed to it and return the result.
In order to demonstrate how to use the function as children pattern in a real application, I’m going to implement a Tween component that will provide the current position of the tween to the Function as a Child.
As an aside, tweening (aka inbetweening) is a way of animating objects by calculating the frames between start and end points in a given duration. A linear tween between the the start and a change in a given duration is easy to calculate:
Each frame, we recalculate the position in-between the two points.
The Tween Component
Let’s start by creating a Tween component that will pass down the current position between a start and end point to the function given to it as its children.
Before I show the component, the way it works is by using a timer to recalculate the tweening function and use setState
to store the calculated value. The render function will just pass that state to its children by executing the child as a function:
Also, yes, I should have used requestNextAnimationFrame.
The Rectangle
We need something visual to Tween, so I’m just going to create a simple rectangle component:
The Tween Component In Use
Let’s see this tweening component in action:
Here we are using our SimpleTween component to tween the rectangle’s x position from 0 to 600. The Function as a Child pattern allows us to create a reusable component that passes down custom data that has it’s own lifecycle.
Wrapping Up
In the next part of this article, we will generalize the Tween component so that we can continuously update the end position and not have to worry about changing the start position so that we can have the Rectangle constantly follow the user’s mouse position.
Ivan Montiel is the founder and CEO of Clarity Hub — a company that integrates with Intercom to give customer success teams real-time suggestions. He is also the UI Architect at Nextiva.