Search code examples
reactjsreact-propsspread-syntax

Spread operator in react component props


Could someone tell me, how it is 3 dot spread does? I know it wanna passing a isActive(Boolean) into Component SideNavLink. If it true then it has those props. But, I'm wondering what the code does.

  1. {} a bracket
  2. 3 dot(spreading) after bracket
  3. () after 3 dot spread

I hope I have a great and clear to describe what I wondering.

 <NavLink href={href}>
      {(isActive) => (
        <SideNavLink
          {...(isActive && { // this spread operator
            bg: "teal.200",
            rounded: "sm",
          })}
          {...props}
        />
      )}
    </NavLink>

Solution

  • The ... spreads the next spreadable item. In your case if you evaluate the isActive to true you will find,

    ...{bg: "teal.200", rounded: "sm",}
    

    So the spread operator spread this {bg: "teal.200", rounded: "sm",} object and returns bg: "teal.200", rounded: "sm" so that they can be passed as props.