Home > database >  How does JSX render the {foo => [ <bar />, <baz /> ]} syntax?
How does JSX render the {foo => [ <bar />, <baz /> ]} syntax?

Time:03-02

I've just seen the above syntax on a CodeSandbox, and as far as I'd always learned you cannot render arrays in JSX - you must always map them if you want to render something for each of the array items.

Here's the code I saw:

render(
<React.StrictMode>
    <HigherOrderComponent>
        {permissions => [
            <Resource name="posts" {...posts} />,
            <Resource name="comments" {...comments} />,
            permissions ? <Resource name="users" {...users} /> : null,
            <Resource name="tags" {...tags} />,
        ]}
    </HigherOrderComponent>
</React.StrictMode>,
document.getElementById('root')
);

And here's the CSB

How does that permissions inline JavaScript work? I think it's also very curious that permissions is not defined anywhere in the file.

CodePudding user response:

It will just render all of them as sibling nodes

[<Foo/>, <Bar/>]

is equivalent to

<>
  <Foo/>
  <Bar/>
</>

For example, this will render as <p>hello</p><p>world</p>

const App = () => [
  <p>hello</p>,
  <p>world</p>,
];
ReactDOM.render(<App/>, document.querySelector('#root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

CodePudding user response:

This depends entirely on what HigherOrderComponent does. Since React doesn't limit children of an element to actually be JSX elements, you can do just that (or any other function-shape render prop).

I would assume HigherOrderComponent is something like (EDIT: I was more or less correct)

function HigherOrderComponent({children}) {
  const permissions = usePermissions();  // fictional hook to return permissions
  const childFunc = React.Children.only(children);
  const realChildren = childFunc(permissions);
  return <>{realChildren}</>;
}

(see React.Children.only()).

  • Related