Passing {ClassName} vs passing {<ClassName>} as react component porps. What is the difference?

Viewed 45

I'm new to react development. I often came accross code examples where a component takes other component as props, like so:

import AccountCircleIcon from '@material-ui/icons/AccountCircle';
import { UserInfo } from './userinfo';

const UserPanel = (props) => {
    return (
        <UserInfo icon={<AccountCircleIcon/>} user={props.user}>
            {props.children}
        </UserInfo>
    );
}

Other time, I see component that takes class name as one of its props. Like so:

import { Admin } from 'react-admin';
import { AppLayout } from './components';

const App = (props) => {
  return (
    <Admin layout={AppLayout}>
      {* other codes here ... *}
    </Admin>
  );
}

What's the difference? If both approach can be used to achieve the same effect, which one is considered better?

1 Answers

The difference is that on the first code, you're calling the render function on your component and passing the result render as a prop. On the second code, you're sending the component (not rendered yet!) as a prop and will use it to render in another place of your tree.

Essentially they're the same and it's up to how you want to drive passing props on your project.

Just to illustrate, consider that you have two components:


// Returns a JSX.Element
function AccountCircleIcon() {
  return (<>Foo</>)
}

// Also, returns a JSX.Element
function AppLayout() {
  return (<>Bar</>)
}

function App() {
  return (
     <>
      // The two lines below will produce exactly a JSX.Element
      <AccountCircleIcon/>
      {AppLayout()}

      // Dependency prop here will be a valid React component
      // Like a function you can call: AppLayout()
      <AnotherComponent dependency={AppLayout}/>


      // Dependency prop will be also valid React component
      // but it's already rendered.
      <AnotherComponent dependency={<AccountCircleIcon/>}/>
     </>
  )
}

Check this out to understand and play a little bit with the idea.

Related