fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@@ -0,0 +1,74 @@
---
title: Basic Commands
---
## Basic Commands
Here you will find a list of basic commands to start developing iOS and Android apps using React Native. If you don't have it installed yet, is highly recommended that you follow the [official guide](https://facebook.github.io/react-native/docs/getting-started.html).
### Starting a new project
There are different ways you can bootstrap a react native application. You can use **Expo** or `create-react-native-app`(which in turns uses Expo-Cli) to start your new project, but with this method you are in more control of what happend in your project and can communicate, tweak and write your own modules with native libraries for iOS and Android mobile platform.
```
react-native init [PROJECT-NAME]
cd [PROJECT-NAME]
```
**Run app in Android emulator**
This command is self explanatory and as it says it will start the Android emulator and install the app you just created. You need to be in the root of the project to run this command.
```
react-native run-android
```
**Run app in iOS emulator**
This command do exactly the same as `react-native run-android` but instead of the Android emulator, it opens the iPhone simulator.
```
react-native run-ios
```
**Link dependencies to native projects**
Some libraries have dependencies that need to be linked in the native code generated for React Native. If something doesn't work after you installed a new library, maybe is because you skip this step.
```
react-native link [LIBRARY-NAME]
```
**Clear bundle**
If something don't run as expected, maybe you need to clear and create a new bundle with this command.
```
watchman watch-del-all
```
**Support decorators**
JSX doesn't support decorators by default so you need to install the **Babel** plugin to make it work.
```
npm install babel-plugin-transform-decorators-legacy --save
npm install babel-plugin-transform-class-properties --save
```
### Export APK to run in device
With the following commands you will have and unsigned apk so you can install and share with your colleagues for testing purposes. Just remember that this apk is not ready to upload to the App Store or production.
You will find your fresh apk in *android/app/build/outputs/apk/app-debug.apk*
**1. Bundle debug build**
```
react-native bundle --dev false --platform android --entry-file index.android.js --bundle-output ./android/app/build/intermediates/assets/debug/index.android.bundle --assets-dest ./android/app/build/intermediates/res/merged/debug
```
**2. Create debug build**
```
cd android
./gradlew assembleDebug
```

View File

@@ -0,0 +1,66 @@
---
title: Functional vs Class Components
---
## React Native - Functional vs Class Components
In React Native, there are two main types of components that make up an application - *functional components* and *class components*. These are structured the same as they would be in a regular React app for the web.
### Class Components
Class components are JavaScript ES2015 classes that extend a base class from React called `Component`.
```js
class App extends Component {
render () {
return (
<Text>Hello World!</Text>
)
}
}
```
This gives the class `App` access to the React lifecycle methods like `render` as well state/props functionality from the parent.
### Functional Components
Functional components are simpler. They don't manage their own state or have access to the lifecycle methods provided by React Native. They are literally plain old JavaScript functions. They are also known as stateless components.
```js
const PageOne = () => {
return (
<Text>Page One</Text>
);
}
```
Note that its immediate parent doesn't necessarily have to be a Class component. It could just be another stateless one, which allows for better componentization. Here's an example.
```js
const SecondComponent = () => {
return <Text>Hello World</Text>
}
const FirstComponent = () => {
return (
<View>
<SecondComponent />
</View>
)
}
class App extends Component {
render () {
return <FirstComponent />
}
}
```
We're not doing all that much here. `App` is a class component that renders `FirstComponent`, which is just a functional component that returns `SecondComponent` inside of a `View`.
Obviously, if the goal was just to render a `Text` component that said "Hello World", you wouldn't need `FirstComponent` nor `SecondComponent`. But the purpose of this example is to show how one might go about nesting functional components.
Sometimes, a functional component may contain a lot of markup for its configuration. For example, the `TextInput` component can be customized with many attributes, so you may want to create custom components for different fields like email, password, username and so on. That is a powerful concept, as you're now able to reuse these custom components throughout your application.
### Summary
Class components are used as container components to handle state management and wrap child components. Functional components generally are just used for display purposes - these components call functions from parent components to handle user interactions or state updates.

View File

@@ -0,0 +1,39 @@
---
title: Hello World
---
## Hello World
In a traditional webpage, you could easily render `Hello World!` to the screen by writing some HTML like this:
```html
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
```
In React Native, there is no DOM or browser, so you have to render things to the screen from a mobile API that React Native provides. For example, instead of using a `<p>` tag as a wrapper for text like you would on the web, you would use `<Text>`; instead of `<div>` container tags, you would use `<View>`.
```js
import React, { Component } from react;
import { AppRegistry, View, Text } from react-native;
class App extends Component {
render () {
return (
<View>
<Text> Hello World! </Text>
</View>
);
}
}
AppRegistry.registerComponent(AwesomeProject, () => App);
```
To render the code to the screen, instead of opening the page in a browser, you use a special `AppRegistry.registerComponent()` method provided by React Native to render the app to a mobile device.

View File

@@ -0,0 +1,38 @@
---
title: React Native
---
## React Native
React Native is a cross-platform framework for building mobile applications that can run outside of the browsermost commonly iOS and Android applications
It can be used to build applications on Windows devices, desktop OSs, and Apple TV apps as well but this guide will only be covering its most common purposeAndroid and iOS applications.
**Table of Contents**
- [What is React Native?](#what-is-react-native)
- [Reasons to choose React Native](#reasons-to-choose-react-native)
- [How to Get Started with React Native](#how-to-get-started-with-react-native)
### What is React Native
React Native falls in-between native and hybrid applications on the mobile app spectrum. The user interface you create is entirely native and the overall application performance is nearly as good as writing a native app. It also gives you the flexibility to embed web views (webpages) or native code (Java/Kotlin for Android, Objective C/Swift for iOS) inside your applications wherever you want.
It follows the same pattern as React where the views (what you see on the screen) are rendered from the JavaScript files. The difference is that it supplies its own API for handling native mobile views vs the DOM on the web. If you are confused about how this works, follow this guide on freeCodeCamp and it will take you step by step through these concepts.
### Reasons to choose React Native
1. **Code reusability**It uses one code based that is shared between both platforms.
1. **Reuse web tools and skills**Reuse JavaScript knowledge, tools and utilities like `axios`, Redux, and other libraries that dont require the DOM from the web.
1. **Optimized for developer productivity**Comes with features like hot/live module reloading and chrome developer tools for debugging out of the box!
1. **Performance**Performs better than hybrid application frameworks like Ionic and Cordova since it is not using web views.
1. **Corporate backing**Lots of companies support and contribute to React Native including Walmart, Airbnb, Wix, and, of course, Facebook.
1. **Community**React Native has a large (and growing) community with over 1500 contributors to the core project and thousands more who contribute to various libraries.
1. **Better user experience**React Native uses the JavaScript code to render native components from your phone's OS. In other words, the application's user interface (UI) is entirely native!
1. **Cross-Platform** - Great way to prototype and save time while building either a universal user interface or platform specific mobile application that can run on both iOS and Android devices.
### How to Get Started with React Native
There are three quick easy ways to get started with React Native. Depending on your situation, one can be a better option for you.
1. [Create React Native App](https://www.npmjs.com/package/create-react-native-app)- Similar to Create React App it get up in running using the terminal.
1. [Expo](https://expo.io) - Best for prototyping an app or if it is earlier stage. Using Expo you can even create an quick app using drag and drop features from snack.expo.io in the broswer.
1. [Ignite CLI](https://github.com/infinitered/ignite) - Empowers devleopers to easily create a new React Native app with plug ins. Ignite CLI also enables developers to easily setup best practices.

View File

@@ -0,0 +1,70 @@
---
title: Props
---
## React Native - Props
The term props, short for 'properties', means some type of data that is passed from one component into another. Props always flow downward from the parent component to the child.
In React, the child component has access to the information from a parent via props:
```jsx
// the child Header component receives the text prop and can access it via this.props.text
class Header extends Component {
render () {
return (
<Text>{this.props.text}</Text>
)
}
}
class App extends Component {
render () {
return (
<Header text="Welcome!" />
);
}
}
```
This also works the same way in functional components:
```jsx
// in functional components, props will be received as a parameter 'props'
const Header = (props) => {
return (
<Text>{props.title}</Text>
);
};
class App extends Component {
render () {
return (
<View>
<Header text="Welcome!" />
</View>
);
}
}
```
Other libraries you import will also give you access to additional properties inside your components. Here is an example from the [react-native-elements](https://github.com/react-native-training/react-native-elements) library.
```jsx
import { Button } from 'react-native-elements';
// here 'buttonStyle' and 'title' are props passed into the Button component
class App extends Component {
render () {
return (
<Button
buttonStyle={{backgroundColor: 'red', borderRadius: 10}}
title={`Submit`}
/>
);
}
}
```

View File

@@ -0,0 +1,77 @@
---
title: Screen Dimensions
---
## React Native - Screen Dimensions
React Native uses Dots Per Inch (DPI) to measure the sizing of the User Interface (UI) and anything displayed on the UI. This type of measurement allows an application to look uniform across various screen sizes and pixel densities.
For standard use cases, applications can be developed without having to know the specifics of the user's device (e.g. pixel density) since the UI elements will scale automatically. When it is required, there are APIs available such as `PixelRatio` for finding out the pixel density of the user's device.
React Native provides an API called `Dimensions` that can be used to get the width and height of the window or screen of a user's device.
```js
import { Dimensions } from 'react-native';
```
These are are the methods that this API currently offers:
```
set
get
addEventListener
removeEventListener
```
For the purposes of this guide, we'll focus on the `get` method, but feel free to check out the React Native official documentation for details on the other methods.
https://facebook.github.io/react-native/docs/dimensions#docsNav
The width and height of the window object can be easily retrieved, like so:
```js
const width = Dimensions.get("window").width
const height = Dimensions.get("window").height
// if you're feeling fancy, you could also use object destructuring to get those values out of the object that `Dimensions.get("window")` returns
const { width, height } = Dimensions.get("window")
```
Pretty simple, huh? Let's take a look at an example.
Let's say you want to cover the whole screen with a background image. We'll use the `ImageBackground` component that React Native provides. You can read more about it in the link below.
https://facebook.github.io/react-native/docs/images#background-image-via-nesting.
We need to set the width and height for this component to work. One way to do that is by using the width and height we got with the `Dimensions` API.
```js
import React, { Component } from "react"
import { Dimensions, ImageBackground } from "react-native"
const { width, height } = Dimensions.get("window")
export default HomePage = () => {
return(
<ImageBackground source={...} style={{ width, height }}>
</ImageBackground>
)
}
```
What makes React Native so attractive is the ability to write code once and have it run on multiple devices (iPhone, iPad, Pixel, etc), and the `Dimensions` API makes that really easy.
For example, if you wanted a screen to look a certain way on an iPad vs a phone simple math can be done to apply the proper styling.
```js
const { width, height } = Dimensions.get('window');
const TABLET_RATIO = 1.6;
const ASPECT_RATIO = height/width;
// later on in the view this can be applied with a ternary
<FancyView
style={(ASPECT_RATIO > TABLET_RATIO) ? styles.phone : styles.ipad }
></FancyView>
```
**Note: There have been some known issues in the past with the Dimensions API such as not returning the correct information when a user rotates their device. It's best to make sure you test this on actual devices before deploying an application.**

View File

@@ -0,0 +1,75 @@
---
title: Component State
---
## Component State
In `Class` components, there is a way to store and manage state built in to React Native.
```javascript
class App extends Component {
constructor () {
super();
this.state = {
counter: 0
};
}
incrementCount () {
this.setState({
counter: this.state.counter + 1
});
}
decrementCount () {
this.setState({
counter: this.state.counter - 1
});
}
render () {
return (
<View>
<Text>Count: {this.state.counter}</Text>
<Button onPress={this.decrementCount.bind(this)}>-</Button>
<Button onPress={this.incrementCount.bind(this)}>+</Button>
</View>
);
}
}
```
State is similar to props, but it is private and fully controlled by the component. Here, the `constructor()` method is calling the parent class' constructor with `super();` - **`Component`** is the parent class of `App` because we are using the `extends` keyword. The `constructor()` method also initializes the component's state object:
```
this.state = {
counter: 0
};
```
The state can be displayed within the component:
```js
{this.state.counter}
```
Or updated by calling:
```js
this.setState({});
```
**Note:** Aside from its initial creation in your component's `constructor()` method, you should never directly modify the component's state with `this.state = `. You must use `this.setState` as can be seen in the `incrementCount` and `decrementCount` functions above.
The count is incremented and decremented by calling the functions passed to the `onPress` handlers just like they would be if you called a click handler from JavaScript on the web.
*ASIDE: In the first example, `<Button>` is a custom component; it's a combination of `<TouchableOpacity>` and `<Text>` from the React Native API:*
```js
const Button = ({ onPress, children, buttonProps, textProps }) => {
const { buttonStyle, textStyle } = styles;
return (
<TouchableOpacity onPress={onPress} style={[buttonStyle, buttonProps]}>
<Text style={[textStyle, textProps]}>
{children}
</Text>
</TouchableOpacity>
);
};
```

View File

@@ -0,0 +1,117 @@
---
title: Styling
---
## React Native - Styling
React Native provides an API for creating stylesheets and styling your components: [StyleSheet](https://facebook.github.io/react-native/docs/stylesheet).
```jsx
import React, { Component } from 'react';
import { StyleSheet, View, Text } from 'react-native';
export default class App extends Component {
render () {
return (
<View>
<Text style={styles.header}>I am a header!</Text>
<Text style={styles.text}>I am some blue text.</Text>
</View>
);
}
}
const styles = StyleSheet.create({
header: {
fontSize: 20
},
text: {
color: 'blue'
}
});
```
While regular CSS stylesheets aren't valid, React Native's superset of CSS is very similar to traditional CSS. Many CSS properties (e.g. `color`, `height`, `top`, `right`, `bottom`, `left`) are the same in StyleSheet. Any CSS properties that have hyphens (e.g. `font-size`, `background-color`) must be changed to camelCase (e.g. `fontSize`, `backgroundColor`).
Not all CSS properties exist in StyleSheet. Since there is no true concept of hovering on mobile devices, CSS hover properties don't exist in React Native. Instead, React Native provides [Touchable components](https://facebook.github.io/react-native/docs/handling-touches#touchables) that respond to touch events.
Styles are also not inherited as they are in traditional CSS. In most cases, you must declare the style of each component.
### Flexbox Layouts
React Native uses an implementation of [flexbox](https://facebook.github.io/react-native/docs/flexbox) similar to the web standard. By default, items in the view will be set to `display: flex`.
> If you do not want to use flexbox, you can also arrange React Native components via `relative` or `absolute` positioning.
Flexbox in React Native defaults to `flexDirection: column`, instead of `flex-direction: row` (web standard). The `column` value displays flexible items vertically, which accommodates mobile devices in portrait orientation.
To learn more about flexbox, visit [this detailed guide on CSS-Tricks](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) and a gamified learning approach with [Flexbox Froggy](http://flexboxfroggy.com/).
### Styled Components
Including lots of styles in a file with a component isn't always easy to maintain. Styled components can solve this issue.
For example, a Button component may be used in multiple places across an application. Copying and pasting the style object with each Button instance would be inefficient. Instead, create a reusable, styled Button component:
```jsx
import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
const Button = ({ onPress, children }) => {
const { buttonStyle, textStyle } = styles;
return (
<TouchableOpacity onPress={onPress} style={buttonStyle}>
<Text style={textStyle}>
{children}
</Text>
</TouchableOpacity>
);
};
export default Button;
const styles = {
textStyle: {
alignSelf: 'center',
color: '#336633',
fontSize: 16,
fontWeight: '600',
paddingTop: 10,
paddingBottom: 10
},
buttonStyle: {
backgroundColor: '#fff',
borderWidth: 1,
borderColor: '#336633',
paddingTop: 4,
paddingBottom: 4,
paddingRight: 25,
paddingLeft: 25,
marginTop: 10,
width: 300
}
};
```
The styled Button component can be easily imported and used across the application without repeatedly declaring the style object:
```jsx
import React, { Component } from 'react';
import { TextInput, View } from 'react-native';
import Button from './styling/Button';
export default class Login extends Component {
render() {
return (
<View>
<TextInput placeholder='Username or Email' />
<TextInput placeholder='Password' />
<Button>Log In</Button>
</View>
);
}
}
```
### Libraries for Styling
There are a few popular libraries for styling React Native. Some of them provide features similar to [Bootstrap](../../bootstrap/index.md), including default forms, button styles, and page layout options. One of the most popular libraries is [styled-components](https://github.com/styled-components/styled-components). There are many others you can find on npm and GitHub to try for yourself.

View File

@@ -0,0 +1,49 @@
---
title: Touchables
---
## React Native - Touchables
Some of the main features of mobile devices revolve around user touch interactions. How a mobile app handles and responds to these interactions can make or break the user's experience.
React Native ships with a `Button` component which works for many standard `onPress` interactions. By default, it will give the user feedback by changing the opacity to show the button was pressed. Usage:
```js
<Button onPress={handlePress} title="Submit" />
```
For more complex use cases, React Native has APIs build in to handle press interactions called `Touchables`.
```
TouchableHighlight
TouchableNativeFeedback
TouchableOpacity
TouchableWithoutFeedback
```
Each of these Touchable components can be styled and used with a library, like the built-in `Animated`, allowing you to make your own types of custom user feedback.
Some examples of using these components:
```js
// with images
<TouchableHighlight onPress={this.handlePress}>
<Image
style={styles.button}
source={require('./logo.png')}
/>
</TouchableHighlight>
// with text
<TouchableHighlight onPress={this.handlePress}>
<Text>Hello</Text>
</TouchableHighlight>
```
You can handle different types of button presses as well. By default, buttons and touchables are configured to handle regular taps, but you can also denote a function to call for press and hold interactions for example.
```js
<TouchableHighlight onPress={this.handlePress} onLongPress={this.handleLongPress}>
```
To see all of the available props and how these components work, you can look at [the JavaScript source code for Touchables here](https://github.com/facebook/react-native/tree/master/Libraries/Components/Touchable).