Search code examples
reactjsreact-nativejsxreact-propsarrow-functions

Can you explain this react native code (strange arrow function in render method)?


So this is some React Native code from a textbook that I'm going through, specifically it is from the render method of App.js. Of course the /* ...*/ would be filled in with actual code but it's irrelevant to my question.

<MeasureLayout>
        {layout => (
            <KeyboardState layout={layout}>
                {keyboardInfo => /* … */}
            </KeyboardState>
        )}
</MeasureLayout>

What I don't understand is what is happening with {layout => (.... So I take it that layout is an arrow function that returns this keyboardState component. So how does layout then pass itself into keyboardState's layout prop at this part <KeyboardState layout={layout}>? And why would I want to do that exactly? This whole part here is really baffling me.


Solution

  • React components have props and children properties. The children property is usually a React node, but it can also be a function that returns a React node.


    So how does layout then pass itself into keyboardState's layout prop at this part ?

    The MeasureLayout component was created so that its children property was defined as a function instead of a React node.

    And why would I want to do that exactly?

    For dependency injection and as a pattern that allows for a more declarative style of programming with class-based components.


    Some more in depth reading:

    Topic: Functions as children

    https://medium.com/merrickchristensen/function-as-child-components-5f3920a9ace9

    https://codedaily.io/tutorials/6/Using-Functions-as-Children-and-Render-Props-in-React-Components