0

I'm working with React functional component, and in the parameter of that functional component here Deal we are using destructuring. Furthermore, we are doing match : {params}, but I'm unable to get that part. Would anybody please explain!

const Deal = ({ history, form, match: { params } }) => {
     let isLoading = useSelector(getSelectedDealLoading);
     let err = useSelector(getSelectedDealError);
     const isSubmitSuccess = useSelector(getSuccess);
     const [isSubmitted, changeIsSubmitted] = useState(false);
    }
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    It's the same as `(props) => { const history = props.history, form = props.form, params = props.match.params; ... }` – jonrsharpe Aug 31 '20 at 16:45
  • 2
    Does this answer your question? [Destructuring Nested objects in javascript | Destructure second level parent and child Objects](https://stackoverflow.com/questions/54293147/destructuring-nested-objects-in-javascript-destructure-second-level-parent-and) – jonrsharpe Aug 31 '20 at 16:46
  • got it, essentially what you mean is we are destructuring match and only getting params, which may have mor properties!? – Yash Parekh Aug 31 '20 at 16:49
  • 1
    Yes, you won't have access to any of `match`'s other properties as written. – jonrsharpe Aug 31 '20 at 16:51
  • cool, understood, thanx for your help @jonrsharpe – Yash Parekh Aug 31 '20 at 16:52
  • but then why we are using variable params to access that value why not match? – Yash Parekh Aug 31 '20 at 17:02
  • What do you mean *"why"*? You'd have to ask whoever wrote it - presumably to make it clear that's the only part of `match` you're using, or to avoid writing `match.params` inside the function. – jonrsharpe Aug 31 '20 at 17:03

1 Answers1

2

const objectToDestructure = {
  history: 'historyValue',
  form: 'formValue',
  match: {
    params: {
      param1: 'param1Value',
      param2: 'param2Value',
    }
  }
};

const { history, form, match: { params } } = objectToDestructure;

console.log({ history, form, params });

If your function parameters have the structure of the object in my snippet, it should work!

Dom
  • 734
  • 3
  • 8
  • so, in this case match may have more than one property except params, but we are only considering params, does that make sense? – Yash Parekh Aug 31 '20 at 16:50
  • 1
    Exactly! We're only destructuring params from match, nothing else. If you need more than params, just add it into the expression like so: `const { history, form, match: { params, value2, value3 } } = objectToDestructure;` – Dom Aug 31 '20 at 16:52
  • 1
    In my example `params` would be whatever value params has and value2 would be `undefined`. – Dom Aug 31 '20 at 17:01
  • but then why we are using variable params to access that value why not match? – Yash Parekh Aug 31 '20 at 17:02
  • It's just syntactic sugar. You can use `params.foo` throughout your code instead of `match.params.foo` etc. Makes it more readable. – Dom Aug 31 '20 at 17:04