object destructuring react code example

Example 1: javascript object destructuring

//simple example with object------------------------------
let obj = {name: 'Max', age: 22, address: 'Delhi'};
const {name, age} = obj;

console.log(name);
//expected output: "Max"

console.log(age);
//expected output: 22

console.log(address);
//expected output: Uncaught ReferenceError: address is not defined

// simple example with array-------------------------------
let a, b, rest;
[a, b] = [10, 20];

console.log(a);
// expected output: 10

console.log(b);
// expected output: 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: Array [30,40,50]

Example 2: definition destructuring react

const Attraction = ({ auth, attraction }) => {  return (    <div auth={auth} key={attraction.id}>      <Link        token={auth.token}        to={`/attractions/${attraction.url_name}`}        key={attraction.id}      >        <img alt={attraction.name} src={attraction.image_url} />        <h1>{attraction.name}</h1>      </Link>      <StarRatings rating={attraction.average_rating} />    </div>  );};

Example 3: definition destructuring react

props = {      attraction: {      address1: "350 5th Ave",      address2: "",      average_rating: 4,      city: "New York",      country: "US",      display_address: ["350 5th Ave", "New York, NY 10118"],      id: 9,      latitude_coordinate: "40.748442285082",      location: {        created_at: "2018–03–07T03:56:20.717Z",        id: 1,        latitude_coordinate: 40.712775,        longitude_coordinate: -74.005973,        ...      }    },    auth: {      loggedIn: true,      loggingIn: false,      ...    } ...  }

Example 4: definition destructuring react

const Attraction = ({  auth,   auth: { token },  attraction: { id, url_name, name, image_url, average_rating }}) => {  return (    <div auth={auth} key={id}>      <Link token={token} to={`/attractions/${url_name}`} key={id}>        <img alt={name} src={image_url} />        <h1>{name}</h1>      </Link>      <StarRatings rating={average_rating} />    </div>  );};

Example 5: js object destructuring

const { [propName]: identifier } = expression;

Example 6: definition destructuring react

class Attraction extends React.Component {  render() {    const {      auth,      auth: { token },      attraction: { id, url_name, name, image_url, average_rating }    } = this.props;return (      <div auth={auth} key={id}>        <Link token={token} to={`/attractions/${url_name}`} key={id}>          <img alt={name} src={image_url} />          <h1>{name}</h1>        </Link>        <StarRatings rating={average_rating} />      </div>    );  }}