Jayffe
Jayffe

Reputation: 1279

JSX syntax arrow function inside render

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?

Upvotes: 5

Views: 2597

Answers (1)

Tholle
Tholle

Reputation: 112927

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>

Upvotes: 3

Related Questions