5

I just saw this code in this other question and i don't understand how it works :

let Parent = () => (
  <ApiSubscribe>
    {api => <Child api={api} />}
  </ApiSubscribe>
)

I understand something like this:

let Parent = ({api}) => (
  <ApiSubscribe>
    <Child api={api} />
  </ApiSubscribe>
)

but never saw {foo => <Bar bar={bar} />} in render before,

can someone help me understand this?

Jayffe
  • 1,269
  • 9
  • 13
  • 1
    If you want to pass arguments to the children, this pattern is useful because you can do `props.children(api)` in `ApiSubscribe` and pass the argument `api`. – Andrew Li Jul 28 '18 at 19:41

1 Answers1

3

A component can access the child elements given to it with the children prop. If a function is given as child, the component can call this function. The component calling the children function can then call the function with any argument it sees fit.

Example

const Child = props => {
  return props.children('test');
};

const Parent = () => (
  <Child>
    {function(arg1) {
      return <div> This is a {arg1} </div>;
    }}
  </Child>
);

ReactDOM.render(<Parent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • thank's for this explanation, but something is not clear for me, if instead of `{function() { ...`I write `{function(foo) { ...` what will `foo`contains ? Child's props? – Jayffe Jul 28 '18 at 19:47
  • @Jayffe You're welcome! I updated the answer. The component itself can call the `children` function with whatever arguments it likes. It differs from library to library that use this technique. – Tholle Jul 28 '18 at 19:49