React Native ~ Basic components - rohit120582sharma/Documentation GitHub Wiki

Components

React (Native) is a component-based framework. This means that your app is made from lots of components that are nested within each other. You're always have one root component, but inside it we can have as many big or small components as we'd like.

It's generally a really good practice to break your app into components and to make the components as small and standalone as possible. This is handy because:

  1. It promotes component reuse
  2. Easier to follow - no one wants to debug a 1000 line component if they can help it
  3. Easier to test - the smaller the unit, the easier it is to unit test!
import React from 'react';
import { View, Text } from 'react-native';

const ColorBox = (props) => {
  return (
    <View>
      <Text>
        {props.colorName} {props.hexCode}
      </Text>
    </View>
  );
};

export default ColorBox;

Notice that we have to use braces {} around variables in order to display them inside Text. This is so React Native could distinguish between pain text and variables that should be evaluated.



Styling

In React Native, all styling is done using inline styles. We use a StyleSheet from react-native to create the styles. Usually we add this styles constant at the bottom of the file, or in a separate file:

import React from 'react';
import { View, Text, StyleSheet  } from 'react-native';

const ColorBox = (props) => {
  const colorStyle = {
    backgroundColor: props.hexCode,
  };
  return (
    <View style={[styles.container, colorStyle]}>
      <Text style={styles.text}>
        {props.colorName} {props.hexCode}
      </Text>
    </View>
  );
};

export default ColorBox;

const styles = StyleSheet.create({
  container: {
    padding: 10,
    backgroundColor: 'lavender',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 10,
  },
  text: {
    fontWeight: 'bold',
    color: 'white',
  },
});

StyleSheet.create creates an optimized style object where you can access the individual styles like on a regular object.

This is pretty similar to the styles on the web, only we omit the units (px, em, rem etc), because all dimensions in React Native are unit less, and represent density-independent pixels.

In React Native, all positioning is done using FlexBox and all elements have display: flex applied by default.

Notice that the style names in React Native are in camelCase instead of kebab-case, but otherwise are the same as the web!


Styled Components

If you are a fan of styled components, you might be excited to know that they have React Native support! You can even use snake-case like on the web!

Read more about it here.

import styled from 'styled-components/native';

const StyledView = styled.View`
  background-color: lavender;
`;


⚠️ **GitHub.com Fallback** ⚠️