Advanced props handling with REST AND SPREAD OPERATOR.

While reading Road to React(2020) by Robin Wieruch, I got to learn about one of the concise method of passing props from family component to child component. Let's take an example If we have an array of objects for stories,

let initialStories = [
{
title: 'rampage',
author: 'divine',
point: 304,
yearOfPublication: 2027,
objectID: 1
}, {
title: 'monstrel',
author: 'peterson',
point: 314,
yearOfPublication: 2019,
objectID: 2
},
{
title: 'blind',
author: 'ronaldo',
point: 12,
yearOfPublication: 1927,
objectID: 3
}
]

//The lists within the array would be mapped into a list component
import React, {useState} from 'react';

in src/App
function App() {
const [stories, setStories] = useState(initialStories);

return (
<>
<h2>Stories you should read before your 20's</h2>
stories.map(({objectID, ...story) => <List key={objectID} {...items} />);
</>
)
}

function List({title, author, point, yearOfPublication}) {
return (
<>
<h2>{title}</h2>{' '}
<p>{author}<p> {' '} <p>{point}</p>
<strong>{yearOfPublication}</strong>
</>
)
}

stories.map(({objectID, ...story) => ); The trick of rest and spread are used here, Note: rest are always used at the target side of an assignment e.g if we have an object =>

let student = {
firstName: 'ebenezer',
lastName: 'posi',
location: 'Enugu',
age: 18,
educationLevel: Tertiary
}

//To get individual properties and rest the firstname and last name into an array
[location, age, educationLevel, ...studentName] = student;

**Note: The studentName returns a new array 'ebenezer' and 'posi' as element**
**Also Note that => Rest operator must always come as the last element in an array or object **

To use the SPREAD syntax => NOTE: spread syntax are always used at the source side of an assignment if I have three object =>

let profile = {
firstName: 'ebenezer',
lastName: 'bunku',
age: 19
}

let address = {
state: 'Enugu',
city: 'Nsukka',
homeAddress: 'Hilltop',
}

let Student = {Level: 100, ...profile, ...address, department: 'Agricultural Science'}
**The Student Object now, will contain all the information provided within the profile and address object**

With this I hope you understand the concept of Rest operator and Spread syntax. Thanks for Reading