Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 303
Jayffe Avatar asked Oct 17 '22 15:10

Jayffe


1 Answers

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>
like image 75
Tholle Avatar answered Oct 20 '22 15:10

Tholle