-1

I am reviewing some code and was unable to find a breakdown of this arrow function syntax. Could someone help explain what the parameters ({ match, onOpen }: MatchListItemProps) mean?

import React from 'react';
import { ListItem } from 'react-native-elements';
import { StyleSheet } from 'react-native';

type MatchListItemProps = {
  match: User,
  onOpen: Function
};

const styles = StyleSheet.create({});

const TestScreen = ({ match, onOpen }: MatchListItemProps) => {
  const { name, image, message } = match;
  return (....

3 Answers 3

2

Could someone help explain what the parameters ({ match, onOpen }: MatchListItemProps)mean?

This code is using typescript and destructuring. Let me get rid of both for a second, then add them back in. Here it is in pure javascript without destructuring:

const TestScreen = (props) => {
  let match = props.match;
  let onOpen = props.onOpen;

Now i'll add back in the typescript. A variable can be followed by a colon and then a type. This information is used to catch type errors at compile time.

const TestScreen = (props: MatchListItemProps) => {
  let match = props.match;
  let onOpen = props.onOpen;

And then adding in the destructuring. This is a shorthand to pluck values off an object and assign them to local variables:

const TestScreen = ({ match, onOpen }: MatchListItemProps) => {
Sign up to request clarification or add additional context in comments.

Comments

1

Since the parameter is an object, you can deconstruct it inside the parameter.

For instance, take a look at this code

let person = {
   name: 'Felipe',
   age: '23'
}

You could take the values in this form

let name = person.name
let age = person.age

Or you could use a shortcut with destructuring assignment

let { name, age } = person

Finally, if the variable person inside a parameter, you can deconstruct it inside the very parameter

logPersonNameAndAge = ({ name, age }) => {
   console.log(name)
   console.log(age) 
}

So that you could call it passing the entire object

logPersonNameAndAge(person)

Comments

0

Your code is TypeScript, not just JavaScript. : MatchListItemProps is a type annotation that's used by TypeScript, which is used to catch many common errors at compile time instead of at runtime. ({ match, onOpen }) => { ... is a destructuring, which means the function takes an object, and brings into scope variables called match and onOpen containing whatever was in the object with those names. It's roughly equivalent to obj => { let match = obj.match, onOpen = obj.onOpen; .... In turn, const TestScreen = obj => { ... is a lambda, which is roughly equivalent to function TestScreen(obj) { ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.