Function as a Child By Example — Part 2
A practical approach to Function as Children in React
In the last article, I went over how to write a tween component that uses the Function as a Child pattern. In this part, I’d like to expand on that component so that we can build a little app where the rectangle will tween to the current mouse position.
The plan here is to use the Function as a Child pattern to pass down the current mouse position to two Tween components so that we are constantly tweening a rectangle component to the current mouse position.
Keeping State in the Tween Component
We made a Tween component in the last article, but that component won’t work very well if we constantly change the end position — which we will be doing in order to constantly tween the rectangle to the current mouse position.
Instead of setting the start position of the Tween component, we’ll take a cue from the input component that React provides and use a defaultStart
prop instead. This will set the original start position, but the tween’s current position won’t change when we change the end prop.
The other main change will be adding a componentWillReceiveProps
function that will take care of maintaining the current position of the tween when we change the end prop.
One other minor change I made to the above Tween component compared to the original SimpleTween component was that I made the type of tween function to use a prop of the component, so that the linear
tween function is no longer hardcoded.
Using Function as a Child for the Mouse Position
Next we’ll create a MousePosition component that will use the Function as a Child pattern. We’ll add an event listener to the document and use setState
to track the mouse’s x and y coordinates.
Bringing it Together
Now that we have two Function as a Child components, we can compose them together to have our Rectangle component constantly tween to the current mouse position:
Here we used two Tween components, one to track the tween for the x coordinate, and another to track the y coordinate.
Wrapping It All Up
Using the Function as a Child pattern is easy and makes animations and dynamic data easy to pass down your component tree.
One main note to make is that there is also the render-prop pattern, which is similar, expect instead of passing the function to render as a child of the component, you instead use a prop called render
to pass the function down. The concepts are the same, but the semantics are different.
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.