Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '...' in React-Native mean?

A piece of react-native code:

enderScene(route, navigator) {
   let Component = route.component;
   return (
      <Component {...route.params} navigator={navigator}></Component>
   );
}

this code returns a Component Object ,

But I don't understand this code ---> {...route.params}

Question:

  1. What is meant by '...' ?
  2. Can you tell me what is meant by " {...route.params}" ?
like image 513
user5465320 Avatar asked Oct 19 '16 07:10

user5465320


2 Answers

The '...' is called Spread syntax.

The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

Example :

var car = ["door", "motor", "wheels"];
var truck = [...car, "something", "biggerthancar"];

// truck  = ["door", "motor", "wheels", "something", "biggerthancar"]

If you want to know more about spread operator :

https://rainsoft.io/how-three-dots-changed-javascript/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

like image 170
Nicolas Menettrier Avatar answered Sep 22 '22 23:09

Nicolas Menettrier


To expand on the above, in the context of the original post the spread operator is essentially passing through all of the parameters in route.params

For example if route.params was the object

{key: 'my-route', title: 'My Route Title'}

Then

<Component {...route.params} navigator={navigator} />

Could be re-written as

<Component key={route.params.key} title={route.params.title}  navigator={navigator} />

The other "side" of this is the destructuring assignment (example using stateless react components)

const Component = (props) => {
    // this is simply referencing the property by the object key
    let myKey = props.key
    // this is using destructuring and results in the variables key, title and navigator which are from props.key, props.title and props.navigator
    let { key, title, navigator } = props

    return <Text>{title}</Text>
}

You can also do this in the function declaration like so which achieves the same thing

const Component = ({key, title, navigator}) => {
    // now you have variables key, title and navigator 
    return <Text>{title}</Text>
}

See Destructuring

like image 27
Sam Parmenter Avatar answered Sep 25 '22 23:09

Sam Parmenter