Home > Back-end >  Writing Element({...props}) instead of Element(props)
Writing Element({...props}) instead of Element(props)

Time:02-20

I saw somewhere this notation function Element({...props}), but you could also simply write function Element(props). Why should you write this with spread notation?

function Element({...props}) {
  // render element here
}

versus

function Element(props) {
  // render element here
}

CodePudding user response:

You might take a few props later and leave the rest:

function Component({ foo, bar, ...props }) {

Doing this ahead of time might save you some typing later. This is the only thing I can think of why you would do this.

CodePudding user response:

It is called a spread operator

You can use the ES6 Spread operator to pass props to a React component. Let's take an example for a component that expects two props:

function App() {
  return <Hello firstName="Ahmed" lastName="Bouchefra" />;
}

Using the Spread operator, you would write the following code instead:

function App() {
  const props = {firstName: 'Ahmed', lastName: 'Bouchefra'};
  return <Hello {...props} />;
}

This explanation is from here

  • Related