Search code examples
reactjsreact-nativeconstantscoding-stylevar

How to make a constant that holds a piece of react native code


I am new to react native. After installing the default react natives files. I wanted to analyze their way of coding. I noticed that to produce clean code, they use constants to store particular pieces of codes

Default react native example after installing:

 const Section = ({children, title}): Node => {
  const isDarkMode = useColorScheme() === 'dark';
  return (
    <View style={styles.sectionContainer}>
      <Text
        style={[
          styles.sectionTitle,
          {
            color: isDarkMode ? Colors.white : Colors.black,
          },
        ]}>
        {title}
      </Text>
      <Text
        style={[
          styles.sectionDescription,
          {
            color: isDarkMode ? Colors.light : Colors.dark,
          },
        ]}>
        {children}
      </Text>
    </View>
  );
};

I assume that in the above example I copied from the default installed code. Passes the arguments "children" en "title" and then uses it to produce the desired code (kinda like a function call) when referencing/calling "Section". My question is how to do the same thing but without passing the variables? I tried something like this but it isn't allowed

My code:

const header = {
  return (
<View >
  <Image source={require('./Images/img.png')}/>
</View>
);
}

Solution

  • "Kinda like function call" is exactly a function call. It's called arrow functions. Arrow functions are widely used nowadays.

    const myFirstArrowFunction = () => {
        //your function code
    }
    

    And just like any function you only add parameters if you need them.