Search code examples
javascriptreactjscomponentsjsx

Thus returning a JSX necessarily makes the function a component?


I have simple code, I have a component called Feed with some props.

On the main content component called Articles I map through a js object and return Feed component

Now, everyone are using an anonymous function to do so.

<div>
{data.map(()=> <Feed/>))} (sorry if the syntax a bit wrong but you get the idea
</div>

now, I took the function that returns Feed outside the map function

function createFeed (feedData) {
   return <Feed props/>
}

and put it

<div>
{data.map(createFeed)} 
</div>

and it workds wonder, but, thus createFeed is also a component (so I need to change the name to CreateFeed) or is this just a function that return an object to a new array created by the map function thus it's only a function and not a component?


Solution

  • There's no magic here.

    <div>{data.map(createFeed)}</div>
    

    Is equivalent to:

    <div>{ data.map(item => createFeed(item) }</div>
    

    Since the createFeed function returns the component without adding any logic, you can just omit it and return the component. It's all the same.

    Edit:

    In your case, you're merely using the function as a factory, not as a functional component, so you could argue that it doesn't need to be capitalized.

    That is, if you're sure that you won't use the function as a component in Jsx, this is not a problem. If you want to use it as Jsx, this causes a problem, which is documented here: https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized

    If there is no use in having a factory function, I would omit it, but in the end choice is up to you.