1

I am learning React.js. I am familiar with below code

class Login extends Component {
    state = { email: '',};
    render = () => {
        return (//some JSX code);
    }
}

But I got below code as solution of an issue.

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route
      {...rest}
        render={props =>
            (Auth.isAuthenticated() ? ( <Component {...props} />) : (<Redirect to={{ pathname: '/',}}/>))
      }
    />
);

I could not understand above code. Could anyone help me to understand ?

What is {...rest} here?

I know spread operator. Why I am passing it here ({ component: Component, ...rest }) and here <Route {...rest} ? What is it doing in this two places ?

Why the render() is look like this render={props => } ?

Thanks all.

abu abu
  • 6,599
  • 19
  • 74
  • 131
  • `{...rest}` is called [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). When you write `render={props => ... }` you are giving a function to the `render` prop. It might look more obvious at first if you write `render={(props) => { return ... }}` – Tholle Aug 10 '18 at 12:21

2 Answers2

1

{...rest} is a destructuration of an object ref: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment In react you can write component as extension of Component class (managed component) or as extension of PureComponent or Functional Component (unmanaged component). The one you are asking for is a Functional Component. Destructuring is an ES6 feature, while components are react's feature and you can find all info and patterns in react official doc.

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
  • Thanks @Mose Raguzzini. I would like to know more about Functional Component. Could you please help me in this regard ? – abu abu Aug 27 '18 at 08:54
  • 1
    Here we go: https://reactjs.org/docs/components-and-props.html . React's documentation is really well made :) – Mosè Raguzzini Aug 27 '18 at 09:37
0

To answer your first question - it is the Object spread operator, citing MDN:

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

In your case, what it does is the PrivateRoute component passes all the props (except for component) as props to the Route component.

Regarding the second question - this is basically the render props pattern. See the docs for explanation, as it's quite long. But basically what happens is that the Route component takes a function as its render prop, and that function's responsibility is to render some content based on the props passed to it.

Jan Kalfus
  • 5,422
  • 2
  • 30
  • 38