Destructuring Arrays
Destructuring an array into separate components can also be performed using the Spread Syntax.
let original = [1,2,3,4,5,6,7];
let [first, ...remaining] = original;
// Therefore the following will be the values of first and remaining.
first = [1]
remaining = [2,3,4,5,6,7]
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app spread-syntax-demo
Step 2: After creating your project folder, move to it using the following command:
cd spread-syntax-demo
Project Structure: It will look like the following.
Example: The example demonstrate the passing of image props form the parent to the image compoenent using the three dot notation.
Javascript
// Filename - App.js import React from 'react' ; import Image from './Image.jsx' ; function App(props) { const originalImage = { src: "https://media.w3wiki.org/wp-content/cdn-uploads/gfg_200x200-min.png" , alt: "This is a random image" }; const formattedImage = { ...originalImage, height: 300, width: 300 } return ( <div> <Image {...formattedImage} /> </div> ); } export default App; |
Javascript
// Filename - Image.jsx import React from 'react' ; function Image(props) { return ( <div> <img {...props} /> </div> ); } export default Image; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
What do these three dots (…) in React do ?
In React the three dots (…) notation is used as the Spread syntax and Rest parameter that has been part of React for a long time when it could be used via transpilation, although, it has been made a part of JavaScript as part of the ES2015 syntax.
The Spread syntax is used to deconstruct an array or object into separate variables where the exact number of elements in the array may not be known or when we wish to keep an attribute or a set of attributes separate from the entire object.
Three dots (…) can be used as follows:
Table of Content
- Passing attributes
- Inheriting an Object:
- Concatenate Arrays
- Destructuring Arrays
Contact Us