0

I'm studying JavaScript, React Native, and React Navigation. I have just learned about destructuring. It's great, except I don't see the point when there is only one parameter. For example, why not just write

function HomeScreen( navigation ) { /* same code as below */

instead of

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

Thanks for any insights

Michael Rogers
  • 1,318
  • 9
  • 22

2 Answers2

0

Typically functional components will take a props object as an agrument. props might have any number of key value pairs. For example, you might have props.navigation. But writing function HomeScreen( navigation ) is not the same as writing function HomeScreen({ navigation }). Writing { navigation } instead of props in the argument desctuctures the value from its parent object. If you wanted to avoid destructuring, you would write it like this:

function HomeScreen( props ) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => props.navigation.navigate('Details')}
      />
    </View>
  );
}

Again, a react functional component expects to recieve the props object as the argument. We usually call it props, but it could be called anything. This next block is identical, we're just naming props something else:

function HomeScreen( swissArmyKnife ) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => swissArmyKnife .navigation.navigate('Details')}
      />
    </View>
  );
}

For just one parameter, you're right, it's probably not necessary to destructure. Its just a shorthand. But when you have a props object with many many parameters, and you want to pull only certain values from it, it makes more sense. like lets say your props object had parameters navigation, trains, busses, airplanes, bikes, skateboards, and you just want to use a few in your component:

function HomeScreen( {busses, bikes} ) {
  // do some stuff here with busses and bikes, don't worry about the whole props object
}
Seth Lutske
  • 9,154
  • 5
  • 29
  • 78
0

The first argument passed to a React component is the props object made up of all the attributes in the JSX.

<HomeScreen navigation={...} />

It's going to be an object no matter what.

Destructuring is the conventional way to show which props you care about in your component. Some linters will take advantage of that and alert discrepancies between the JSX and the component.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335