1

Im learning react-native. Im completely new to both react and react-native. I`m also javascript beginner, though Im already programming in Java for sometime.

I have this code, and I`m tryng to understand the arrow functions:

export default function App() {


  // A
  const DATA = [
    { id: '123',
      value: 'First Iem'  
    },

    { id: '456',
     value: 'Second Iem'  
   },

   { id: '789',
    value: 'Third Iem'  
   },
 ];

  // B
  const Item = ({myTitle}) => (
    <View>
      <Text>{myTitle}</Text>
    </View>
  );

  // C
  const renderMyItem = ({item}) =>(
    <Item myTitle={item.value}/>
  );

 return (

   <View>   

    // D
    <FlatList
      data={DATA}
      renderItem={renderMyItem}
      keyExtractor={mydata => mydata.id}    
    /> 

  </View>   
  );
}

const styles = StyleSheet.create({

});

What I understand from it is: at A we have an array of objects; each object has an id property and a value property. Thats fine.

But, at B, theres this syntax ({whatever}). If we look at C, we find <Item myTitle={item.value}/>

So, am I right to assume that, by using this syntax ({whatever}) we are able to assign an atributte to an element, like in html we have elements with attributes, such as <img src=""> ?

Also, in C we have the same syntax const renderMyItem = ({item}), and that const renderMyItem is used in D (the FlatList). Am I correct to assume that the FlatList attribute renderItem is takeing an item from DATA and passing it as argument to the const renderMyItem attribute item which, in turn, is given as value to the Item attribute myTitle?

Thanks for your help.

EiteWald
  • 45
  • 4

2 Answers2

0

This is a combination of arrow functions and deconstruction. You have a function that receives an object and by wrapping the parameter you want in curly braces you're able to pull that property off of the object being passed in. In the code below you're calling Item by Using the JSX tag Item and its passing a props object, the ({myTitle}) is deconstructing the myTitle element off of that props object and then making it available for use in the function body.

const Item = ({myTitle}) => (
    <View>
      <Text>{myTitle}</Text>
    </View>
);

<Item myTitle={item.value}/>
osekmedia
  • 553
  • 4
  • 11
0

Ultimately renderItem is getting this:

<FlatList
  data={DATA}
  renderItem={{(item)} => {
    return ( <View>
                 <Text>{item.value}</Text>
             </View> )
  }}
  keyExtractor={mydata => mydata.id}    
/>   

where `item` iterates for every entry that  `DATA` object has, in this case i.e 3.
Rupesh Chaudhari
  • 193
  • 2
  • 2
  • 12