4

I am unable to get why do we use something like {...props}

For example in my code (when I am learning router) I do something like this

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Home from './home.js';

const route = () => {
    return(
        <BrowserRouter>
            <Switch>
                <Route path ="/"  render ={(props) => <Home {...props}/>} />
            </Switch>
        </BrowserRouter>
    )
}

export default route;

Here, this pass on the function/and probably calls it giving him the props

import React from 'react';

const home =  (props) =>  {
  console.log(props)
  return (
  <div> home </div>
  );
}

export default home;

This would log something like this

{match: {…}, location: {…}, history: {…}, staticContext: undefined}

But If I remove {...props} from our home , it won't log this

{match: {…}, location: {…}, history: {…}, staticContext: undefined}

Can anyone please explain in steps/or in length what happens and why do we need it?

Tholle
  • 108,070
  • 19
  • 198
  • 189

2 Answers2

2

The function given to the render prop of a Route is called with the route props listed in the documentation. By spreading them on your Home component, you are just passing these props so they are available in your Home component props as well.

If you are only passing the route props down to the component in the function given to the render prop of the Route, consider using the component prop instead:

<Route path="/" component={Home} />
Tholle
  • 108,070
  • 19
  • 198
  • 189
2

It's basically the spread syntax at work. It lets an iterable to be expanded in places where arguments or parameters are expected.

For example, You have a dict,

params = { a: 1, b: 2, c: 3}

You want a , b and c as props for component Module.

One way to pass them is like this,

<Module a=params['a'] b=params['b'] c=params['c'] />

But utilizing the spread syntax of ES6, it's just this,

<Module {...params} /}

Easier right? Props are just dicts. Your code implies you want Home component to inherit all the props of its parent component Route of which you logged above. You may manually add all those desired props but who has the time for that?

Read more about the spread syntax here.

Franrey Saycon
  • 647
  • 1
  • 5
  • 18
  • You say "Easier right?". I tend to disagree. While the code is shorter and easier to write, it adds indirection, which results in being harder to follow the properties down the component tree. I see this pattern overused in our codebase, where it results in losing track of what properties are passed where, including passing unused properties which are getting lost and not caught unused by linter. Obviously this pattern has it's uses, but be careful to not abuse it to write lazy but hard to follow code. – Robert Kusznier Jun 05 '23 at 17:23