); } function Comment(props" /> ); } function Comment(props" /> ); } function Comment(props"/>

When to use curly braces and when angle in React

426 views Asked by At

For example:

function Avatar(props) {
  return (
    <img className="Avatar"
      src={props.user.avatarUrl}
      alt={props.user.name}
    />
  );
}

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <Avatar user={props.author} />
        <div className="UserInfo-name">
          {props.author.name}

Why can't I use {Avatar(props.author)} or {Avatar() user={props.author}}? I know that I can use functions inside curly bracets, how it works?

2

There are 2 answers

0
codereview On

Well, if the child receive props and return jsx it will be considered as React Element or React Node, in this case you can use it like <Avatar user={props.author} />.

If you want to use functions inside Comment simply like this:

function renderAvatar(author) {
     return ...
}

Comment Component

   <div>
      {renderAvatar(props.author)}
   </div>
0
Andrew Kruglik On

I've found the answer: declaring function as <Component/>, makes it visible to React and allow you to use lifecycle methods and hooks. If you use it as function: React only see the result that returns from it, but it works ~45 times faster.

Thanks everyone for your help!