Search code examples
javascriptreactjsreact-bootstrapspread-syntax

What does the '...rest' stand for in this object destructuring?


I'm reading about unknown-prop warnings in react, particularly because I'm using the react-bootstrap package and have stumbled upon them there.

i've read that: 'To fix this, composite components should "consume" any prop that is intended for the composite component and not intended for the child component', on here:

https://gist.github.com/jimfb/d99e0678e9da715ccf6454961ef04d1b

and an example is given for how the spread operator can be used to pull variables off props, and put the remaining props into a variable.

the example code:

function MyDiv(props) {
  const { layout, ...rest } = props
  if (layout === 'horizontal') {
    return <div {...rest} style={getHorizontalStyle()} />
  } else {
    return <div {...rest} style={getVerticalStyle()} />
  }
}

Here is what the PROBLEM is: In the example given, I don't understand what the '...rest' in this code here stands for. I get that the '...' = spread syntax, but where did the word 'rest' come from and what does it stand for?


Solution

  • This is object rest syntax, it creates an object from all properties that weren't explicitly destructured.

    const obj = { a: 1, b: 2, c: 3};
    
    const { a, ...everythingElse } = obj;
    
    console.log(a);
    
    console.log(everythingElse);

    It's equivalent to array rest syntax:

    const arr = [1, 2, 3];
    
    const [a, ...rest] = arr;
    
    console.log(a);
    console.log(rest);