Spread operator in react component props

2.4k Views Asked by At

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>
2

There are 2 best solutions below

1
On BEST ANSWER

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.

0
On

To explain the spread operator in simple words, it spreads all the properties inside your component.

lets say, you pass a property title = "Side Link", this gets automatically assigned into the Side Nave link component so you don't need to specifically add this prop to retrieve the value.

If you had multiple props passed from parent, and you don't want to manually add them all in the Side Nav Link component, you can use the spread operator and it will spread all those props to the component.

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