diff --git a/css/react-native.css b/css/react-native.css index 7ff24fb0a42..8c4a8b13389 100644 --- a/css/react-native.css +++ b/css/react-native.css @@ -1048,7 +1048,7 @@ h2 { display: table-cell; } p { - margin: 10px 0; } + margin: 16px 0; } .highlight { padding: 10px; @@ -1355,6 +1355,7 @@ div[data-twttr-id] iframe { margin-left: 20px; } .prop { + word-wrap: break-word; padding: 5px 10px; } .compactProps .prop { @@ -1668,6 +1669,14 @@ input#algolia-doc-search:focus { font-size: 24px; text-align: center; } +@media only screen and (max-width: 680px) { + .hero .text { + font-size: 200%; + text-align: center; } + .hero .minitext { + font-size: 18px; + text-align: center; } } + .buttons-unit { margin-top: 40px; text-align: center; } @@ -1676,10 +1685,14 @@ input#algolia-doc-search:focus { color: #FA6900; } .buttons-unit .button { - font-size: 24px; background: #05A5D1; color: #fafafa; } +@media screen and (min-width: 600px) { + .buttons-unit .button { + font-size: 24px; } +} + .buttons-unit .button:active { background: #0485A9; } @@ -1712,15 +1725,11 @@ input#algolia-doc-search:focus { .showcase { margin: 30px auto 30px auto; - width: 100%; + width: 50%; display: inline-block; text-align: center; vertical-align: top; } -@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) { - .showcase { - width: 50%; } } - @media only screen and (min-device-width: 1024px) { .showcase { width: 25%; } } @@ -1832,6 +1841,10 @@ input#algolia-doc-search:focus { display: block; text-align: left; } +@media screen and (max-width: 768px) { + .entry-share { + display: none; } } + .entry-excerpt { min-width: 320px; max-width: 640px; @@ -1903,7 +1916,7 @@ article li { .posted-on { font-size: 12px; - color: rgba(102, 99, 122, 0.29); + color: #9d9b9b; margin-bottom: 0; margin-top: 15px; } @@ -1918,7 +1931,7 @@ article li { color: #5A6B77; } .name-title .title { - color: rgba(102, 99, 122, 0.44); } + color: #9d9b9b; } .btn { background: 0 0; diff --git a/docs/accessibility.html b/docs/accessibility.html index 2d9078c40a7..a3168a735dc 100644 --- a/docs/accessibility.html +++ b/docs/accessibility.html @@ -1,4 +1,4 @@ -Accessibility

Accessibility #

Native App Accessibility (iOS and Android) #

Both iOS and Android provide APIs for making apps accessible to people with disabilities. In addition, both platforms provide bundled assistive technologies, like the screen readers VoiceOver (iOS) and TalkBack (Android) for the visually impaired. Similarly, in React Native we have included APIs designed to provide developers with support for making apps more accessible. Take note, iOS and Android differ slightly in their approaches, and thus the React Native implementations may vary by platform.

In addition to this documentation, you might find this blog post about React Native accessibility to be useful.

Making Apps Accessible #

Accessibility properties #

accessible (iOS, Android) #

When true, indicates that the view is an accessibility element. When a view is an accessibility element, it groups its children into a single selectable component. By default, all touchable elements are accessible.

On Android, ‘accessible={true}’ property for a react-native View will be translated into native ‘focusable={true}’.

<View accessible={true}> +Accessibility

Accessibility #

Native App Accessibility (iOS and Android) #

Both iOS and Android provide APIs for making apps accessible to people with disabilities. In addition, both platforms provide bundled assistive technologies, like the screen readers VoiceOver (iOS) and TalkBack (Android) for the visually impaired. Similarly, in React Native we have included APIs designed to provide developers with support for making apps more accessible. Take note, iOS and Android differ slightly in their approaches, and thus the React Native implementations may vary by platform.

In addition to this documentation, you might find this blog post about React Native accessibility to be useful.

Making Apps Accessible #

Accessibility properties #

accessible (iOS, Android) #

When true, indicates that the view is an accessibility element. When a view is an accessibility element, it groups its children into a single selectable component. By default, all touchable elements are accessible.

On Android, ‘accessible={true}’ property for a react-native View will be translated into native ‘focusable={true}’.

<View accessible={true}> <Text>text one</Text> <Text>text two</Text> </View>

In the above example, we can't get accessibility focus separately on 'text one' and 'text two'. Instead we get focus on a parent view with 'accessible' property.

accessibilityLabel (iOS, Android) #

When a view is marked as accessible, it is a good practice to set an accessibilityLabel on the view, so that people who use VoiceOver know what element they have selected. VoiceOver will read this string when a user selects the associated element.

To use, set the accessibilityLabel property to a custom string on your View:

<TouchableOpacity accessible={true} accessibilityLabel={'Tap me!'} onPress={this._onPress}> @@ -55,6 +55,6 @@ On the other hand, if view B contains a child view C a apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/accessibilityinfo.html b/docs/accessibilityinfo.html index d7efeb626c9..a7e71447699 100644 --- a/docs/accessibilityinfo.html +++ b/docs/accessibilityinfo.html @@ -1,4 +1,4 @@ -AccessibilityInfo

AccessibilityInfo #

Sometimes it's useful to know whether or not the device has a screen reader that is currently active. The +AccessibilityInfo

AccessibilityInfo #

Sometimes it's useful to know whether or not the device has a screen reader that is currently active. The AccessibilityInfo API is designed for this purpose. You can use it to query the current state of the screen reader as well as to register to be notified when the state of the screen reader changes.

Here's a small example illustrating how to use AccessibilityInfo:

class ScreenReaderStatusExample extends React.Component { state = { @@ -59,6 +59,6 @@ reader is enabled and false otherwise.
\ No newline at end of file + \ No newline at end of file diff --git a/docs/actionsheetios.html b/docs/actionsheetios.html index d8d6726ec80..abcd2f11f9a 100644 --- a/docs/actionsheetios.html +++ b/docs/actionsheetios.html @@ -1,210 +1,9 @@ -ActionSheetIOS

ActionSheetIOS #

Methods #

static showActionSheetWithOptions(options, callback) #

Display an iOS action sheet. The options object must contain one or more +ActionSheetIOS

ActionSheetIOS #

Methods #

static showActionSheetWithOptions(options, callback) #

Display an iOS action sheet. The options object must contain one or more of:

  • options (array of strings) - a list of button titles (required)
  • cancelButtonIndex (int) - index of cancel button in options
  • destructiveButtonIndex (int) - index of destructive button in options
  • title (string) - a title to show above the action sheet
  • message (string) - a message to show below the title

static showShareActionSheetWithOptions(options, failureCallback, successCallback) #

Display the iOS share sheet. The options object should contain one or both of message and url and can additionally have a subject or excludedActivityTypes:

  • url (string) - a URL to share
  • message (string) - a message to share
  • subject (string) - a subject for the message
  • excludedActivityTypes (array) - the activities to exclude from the ActionSheet

NOTE: if url points to a local file, or is a base64-encoded uri, the file it points to will be loaded and shared directly. -In this way, you can share images, videos, PDF files, etc.

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - ActionSheetIOS, - StyleSheet, - takeSnapshot, - Text, - View, -} = ReactNative; - -var BUTTONS = [ - 'Option 0', - 'Option 1', - 'Option 2', - 'Delete', - 'Cancel', -]; -var DESTRUCTIVE_INDEX = 3; -var CANCEL_INDEX = 4; - -class ActionSheetExample extends React.Component { - state = { - clicked: 'none', - }; - - render() { - return ( - <View> - <Text onPress={this.showActionSheet} style={style.button}> - Click to show the ActionSheet - </Text> - <Text> - Clicked button: {this.state.clicked} - </Text> - </View> - ); - } - - showActionSheet = () => { - ActionSheetIOS.showActionSheetWithOptions({ - options: BUTTONS, - cancelButtonIndex: CANCEL_INDEX, - destructiveButtonIndex: DESTRUCTIVE_INDEX, - }, - (buttonIndex) => { - this.setState({ clicked: BUTTONS[buttonIndex] }); - }); - }; -} - -class ActionSheetTintExample extends React.Component { - state = { - clicked: 'none', - }; - - render() { - return ( - <View> - <Text onPress={this.showActionSheet} style={style.button}> - Click to show the ActionSheet - </Text> - <Text> - Clicked button: {this.state.clicked} - </Text> - </View> - ); - } - - showActionSheet = () => { - ActionSheetIOS.showActionSheetWithOptions({ - options: BUTTONS, - cancelButtonIndex: CANCEL_INDEX, - destructiveButtonIndex: DESTRUCTIVE_INDEX, - tintColor: 'green', - }, - (buttonIndex) => { - this.setState({ clicked: BUTTONS[buttonIndex] }); - }); - }; -} - -class ShareActionSheetExample extends React.Component { - state = { - text: '' - }; - - render() { - return ( - <View> - <Text onPress={this.showShareActionSheet} style={style.button}> - Click to show the Share ActionSheet - </Text> - <Text> - {this.state.text} - </Text> - </View> - ); - } - - showShareActionSheet = () => { - ActionSheetIOS.showShareActionSheetWithOptions({ - url: this.props.url, - message: 'message to go with the shared url', - subject: 'a subject to go in the email heading', - excludedActivityTypes: [ - 'com.apple.UIKit.activity.PostToTwitter' - ] - }, - (error) => alert(error), - (completed, method) => { - var text; - if (completed) { - text = `Shared via ${method}`; - } else { - text = 'You didn\'t share'; - } - this.setState({text}); - }); - }; -} - -class ShareScreenshotExample extends React.Component { - state = { - text: '' - }; - - render() { - return ( - <View> - <Text onPress={this.showShareActionSheet} style={style.button}> - Click to show the Share ActionSheet - </Text> - <Text> - {this.state.text} - </Text> - </View> - ); - } - - showShareActionSheet = () => { - // Take the snapshot (returns a temp file uri) - takeSnapshot('window').then((uri) => { - // Share image data - ActionSheetIOS.showShareActionSheetWithOptions({ - url: uri, - excludedActivityTypes: [ - 'com.apple.UIKit.activity.PostToTwitter' - ] - }, - (error) => alert(error), - (completed, method) => { - var text; - if (completed) { - text = `Shared via ${method}`; - } else { - text = 'You didn\'t share'; - } - this.setState({text}); - }); - }).catch((error) => alert(error)); - }; -} - -var style = StyleSheet.create({ - button: { - marginBottom: 10, - fontWeight: '500', - } -}); - -exports.title = 'ActionSheetIOS'; -exports.description = 'Interface to show iOS\' action sheets'; -exports.examples = [ - { - title: 'Show Action Sheet', - render(): React.Element<any> { return <ActionSheetExample />; } - }, - { - title: 'Show Action Sheet with tinted buttons', - render(): React.Element<any> { return <ActionSheetTintExample />; } - }, - { - title: 'Show Share Action Sheet', - render(): React.Element<any> { - return <ShareActionSheetExample url="https://code.facebook.com" />; - } - }, - { - title: 'Share Local Image', - render(): React.Element<any> { - return <ShareActionSheetExample url="bunny.png" />; - } - }, - { - title: 'Share Screenshot', - render(): React.Element<any> { - return <ShareScreenshotExample />; - } - } -];
\ No newline at end of file + \ No newline at end of file diff --git a/docs/activityindicator.html b/docs/activityindicator.html index 3571c625ed8..1bdd260612c 100644 --- a/docs/activityindicator.html +++ b/docs/activityindicator.html @@ -1,186 +1,8 @@ -ActivityIndicator

ActivityIndicator #

Displays a circular loading indicator.

Props #

animating?: bool #

Whether to show the indicator (true, the default) or hide it (false).

color?: color #

The foreground color of the spinner (default is gray).

size?: enum('small', 'large'), number #

Size of the indicator (default is 'small'). -Passing a number to the size prop is only supported on Android.

ioshidesWhenStopped?: bool #

Whether the indicator should hide when not animating (true by default).

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -import React, { Component } from 'react'; -import { ActivityIndicator, StyleSheet, View } from 'react-native'; - -/** - * Optional Flowtype state and timer types definition - */ -type State = { animating: boolean; }; -type Timer = number; - -class ToggleAnimatingActivityIndicator extends Component { - /** - * Optional Flowtype state and timer types - */ - state: State; - _timer: Timer; - - constructor(props) { - super(props); - this.state = { - animating: true, - }; - } - - componentDidMount() { - this.setToggleTimeout(); - } - - componentWillUnmount() { - clearTimeout(this._timer); - } - - setToggleTimeout() { - this._timer = setTimeout(() => { - this.setState({animating: !this.state.animating}); - this.setToggleTimeout(); - }, 2000); - } - - render() { - return ( - <ActivityIndicator - animating={this.state.animating} - style={[styles.centering, {height: 80}]} - size="large" - /> - ); - } -} - - - -exports.displayName = (undefined: ?string); -exports.framework = 'React'; -exports.title = '<ActivityIndicator>'; -exports.description = 'Animated loading indicators.'; - -exports.examples = [ - { - title: 'Default (small, white)', - render() { - return ( - <ActivityIndicator - style={[styles.centering, styles.gray]} - color="white" - /> - ); - } - }, - { - title: 'Gray', - render() { - return ( - <View> - <ActivityIndicator - style={[styles.centering]} - /> - <ActivityIndicator - style={[styles.centering, {backgroundColor: '#eeeeee'}]} - /> - </View> - ); - } - }, - { - title: 'Custom colors', - render() { - return ( - <View style={styles.horizontal}> - <ActivityIndicator color="#0000ff" /> - <ActivityIndicator color="#aa00aa" /> - <ActivityIndicator color="#aa3300" /> - <ActivityIndicator color="#00aa00" /> - </View> - ); - } - }, - { - title: 'Large', - render() { - return ( - <ActivityIndicator - style={[styles.centering, styles.gray]} - size="large" - color="white" - /> - ); - } - }, - { - title: 'Large, custom colors', - render() { - return ( - <View style={styles.horizontal}> - <ActivityIndicator - size="large" - color="#0000ff" - /> - <ActivityIndicator - size="large" - color="#aa00aa" - /> - <ActivityIndicator - size="large" - color="#aa3300" - /> - <ActivityIndicator - size="large" - color="#00aa00" - /> - </View> - ); - } - }, - { - title: 'Start/stop', - render() { - return <ToggleAnimatingActivityIndicator />; - } - }, - { - title: 'Custom size', - render() { - return ( - <ActivityIndicator - style={[styles.centering, {transform: [{scale: 1.5}]}]} - size="large" - /> - ); - } - }, - { - platform: 'android', - title: 'Custom size (size: 75)', - render() { - return ( - <ActivityIndicator - style={styles.centering} - size={75} - /> - ); - } - }, -]; - - -const styles = StyleSheet.create({ - centering: { - alignItems: 'center', - justifyContent: 'center', - padding: 8, - }, - gray: { - backgroundColor: '#cccccc', - }, - horizontal: { - flexDirection: 'row', - justifyContent: 'space-around', - padding: 8, - }, -});

ActivityIndicator #

Displays a circular loading indicator.

Props #

animating?: PropTypes.bool #

Whether to show the indicator (true, the default) or hide it (false).

color?: color #

The foreground color of the spinner (default is gray).

size?: PropTypes.oneOfType([ + PropTypes.oneOf([ 'small', 'large' ]), + PropTypes.number, +]) #

Size of the indicator (default is 'small'). +Passing a number to the size prop is only supported on Android.

ioshidesWhenStopped?: PropTypes.bool #

Whether the indicator should hide when not animating (true by default).

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file + \ No newline at end of file diff --git a/docs/adsupportios.html b/docs/adsupportios.html index c3e9bd94947..52e6c45b4e3 100644 --- a/docs/adsupportios.html +++ b/docs/adsupportios.html @@ -1,90 +1,9 @@ -AdSupportIOS

AdSupportIOS #

Methods #

static getAdvertisingId(onSuccess, onFailure) #

static getAdvertisingTrackingEnabled(onSuccess, onFailure) #

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - AdSupportIOS, - StyleSheet, - Text, - View, -} = ReactNative; - -exports.framework = 'React'; -exports.title = 'Advertising ID'; -exports.description = 'Example of using the ad support API.'; - -exports.examples = [ - { - title: 'Ad Support IOS', - render: function(): React.Element<any> { - return <AdSupportIOSExample />; - }, - } -]; - -class AdSupportIOSExample extends React.Component { - state = { - deviceID: 'No IDFA yet', - hasAdvertiserTracking: 'unset', - }; - - componentDidMount() { - AdSupportIOS.getAdvertisingId( - this._onDeviceIDSuccess, - this._onDeviceIDFailure - ); - - AdSupportIOS.getAdvertisingTrackingEnabled( - this._onHasTrackingSuccess, - this._onHasTrackingFailure - ); - } - - _onHasTrackingSuccess = (hasTracking) => { - this.setState({ - 'hasAdvertiserTracking': hasTracking, - }); - }; - - _onHasTrackingFailure = (e) => { - this.setState({ - 'hasAdvertiserTracking': 'Error!', - }); - }; - - _onDeviceIDSuccess = (deviceID) => { - this.setState({ - 'deviceID': deviceID, - }); - }; - - _onDeviceIDFailure = (e) => { - this.setState({ - 'deviceID': 'Error!', - }); - }; - - render() { - return ( - <View> - <Text> - <Text style={styles.title}>Advertising ID: </Text> - {JSON.stringify(this.state.deviceID)} - </Text> - <Text> - <Text style={styles.title}>Has Advertiser Tracking: </Text> - {JSON.stringify(this.state.hasAdvertiserTracking)} - </Text> - </View> - ); - } -} - -var styles = StyleSheet.create({ - title: { - fontWeight: '500', - }, -});

AdSupportIOS #

AdSupport provides access to the "advertising identifier". If you link this library +in your project, you may need to justify your use for this identifier when submitting +your application to the App Store.

In order to use AdSupport in your project, you must link the RCTAdSupport library. +In Xcode, you can manually add the RCTAdSupport.m and RCTAdSupport.h files from +node_modules/react-native/Libraries/AdSupport/ to the Libraries/React/Base/ folder +of your current project.

You can refer to Linking for help.

Methods #

static getAdvertisingId(onSuccess, onFailure) #

static getAdvertisingTrackingEnabled(onSuccess, onFailure) #

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file + \ No newline at end of file diff --git a/docs/alert.html b/docs/alert.html index 4781d1aeae1..15f32b83bb1 100644 --- a/docs/alert.html +++ b/docs/alert.html @@ -1,4 +1,4 @@ -Alert

Alert #

Launches an alert dialog with the specified title and message.

Optionally provide a list of buttons. Tapping any button will fire the +Alert

Alert #

Launches an alert dialog with the specified title and message.

Optionally provide a list of buttons. Tapping any button will fire the respective onPress callback and dismiss the alert. By default, the only button will be an 'OK' button.

This is an API that works both on iOS and Android and can show static alerts. To show an alert that prompts the user to enter some information, @@ -18,142 +18,7 @@ i.e. { cancelable: false }

Example usage:

{text: 'OK', onPress: () => console.log('OK Pressed')}, ], { cancelable: false } -)

Methods #

static alert(title, message?, buttons?, options?, type?) #

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - Alert, - StyleSheet, - Text, - TouchableHighlight, - View, -} = ReactNative; - -var UIExplorerBlock = require('./UIExplorerBlock'); - -// corporate ipsum > lorem ipsum -var alertMessage = 'Credibly reintermediate next-generation potentialities after goal-oriented ' + - 'catalysts for change. Dynamically revolutionize.'; - -/** - * Simple alert examples. - */ -class SimpleAlertExampleBlock extends React.Component { - render() { - return ( - <View> - <TouchableHighlight style={styles.wrapper} - onPress={() => Alert.alert( - 'Alert Title', - alertMessage, - )}> - <View style={styles.button}> - <Text>Alert with message and default button</Text> - </View> - </TouchableHighlight> - <TouchableHighlight style={styles.wrapper} - onPress={() => Alert.alert( - 'Alert Title', - alertMessage, - [ - {text: 'OK', onPress: () => console.log('OK Pressed!')}, - ] - )}> - <View style={styles.button}> - <Text>Alert with one button</Text> - </View> - </TouchableHighlight> - <TouchableHighlight style={styles.wrapper} - onPress={() => Alert.alert( - 'Alert Title', - alertMessage, - [ - {text: 'Cancel', onPress: () => console.log('Cancel Pressed!')}, - {text: 'OK', onPress: () => console.log('OK Pressed!')}, - ] - )}> - <View style={styles.button}> - <Text>Alert with two buttons</Text> - </View> - </TouchableHighlight> - <TouchableHighlight style={styles.wrapper} - onPress={() => Alert.alert( - 'Alert Title', - null, - [ - {text: 'Foo', onPress: () => console.log('Foo Pressed!')}, - {text: 'Bar', onPress: () => console.log('Bar Pressed!')}, - {text: 'Baz', onPress: () => console.log('Baz Pressed!')}, - ] - )}> - <View style={styles.button}> - <Text>Alert with three buttons</Text> - </View> - </TouchableHighlight> - <TouchableHighlight style={styles.wrapper} - onPress={() => Alert.alert( - 'Foo Title', - alertMessage, - '..............'.split('').map((dot, index) => ({ - text: 'Button ' + index, - onPress: () => console.log('Pressed ' + index) - })) - )}> - <View style={styles.button}> - <Text>Alert with too many buttons</Text> - </View> - </TouchableHighlight> - <TouchableHighlight style={styles.wrapper} - onPress={() => Alert.alert( - 'Alert Title', - null, - [ - {text: 'OK', onPress: () => console.log('OK Pressed!')}, - ], - { - cancelable: false - } - )}> - <View style={styles.button}> - <Text>Alert that cannot be dismissed</Text> - </View> - </TouchableHighlight> - </View> - ); - } -} - -class AlertExample extends React.Component { - static title = 'Alert'; - - static description = 'Alerts display a concise and informative message ' + - 'and prompt the user to make a decision.'; - - render() { - return ( - <UIExplorerBlock title={'Alert'}> - <SimpleAlertExampleBlock /> - </UIExplorerBlock> - ); - } -} - -var styles = StyleSheet.create({ - wrapper: { - borderRadius: 5, - marginBottom: 5, - }, - button: { - backgroundColor: '#eeeeee', - padding: 10, - }, -}); - -module.exports = { - AlertExample, - SimpleAlertExampleBlock, -};
\ No newline at end of file + \ No newline at end of file diff --git a/docs/alertios.html b/docs/alertios.html index 8beaf2b2cac..321d46210ad 100644 --- a/docs/alertios.html +++ b/docs/alertios.html @@ -1,4 +1,4 @@ -AlertIOS

AlertIOS #

AlertIOS provides functionality to create an iOS alert dialog with a +AlertIOS

AlertIOS #

AlertIOS provides functionality to create an iOS alert dialog with a message or create a prompt for user input.

Creating an iOS alert:

AlertIOS.alert( 'Sync Complete', 'All your data are belong to us.' @@ -43,181 +43,7 @@ cross-platform support if you don't need to create iOS-only prompts.

=> console.log("Your username is "+text), null, 'default' -);

Type Definitions #

AlertType #

An Alert button type

Type:
$Enum

Constants:
ValueDescription
default

Default alert with no inputs

plain-text

Plain text input alert

secure-text

Secure text input alert

login-password

Login and password alert

AlertButtonStyle #

An Alert button style

Type:
$Enum

Constants:
ValueDescription
default

Default button style

cancel

Cancel button style

destructive

Destructive button style

ButtonsArray #

Array or buttons

Type:
Array

Properties:
Name and TypeDescription
[text]

string

Button label

[onPress]

function

Callback function when button pressed

[style]

Button style


Constants:
ValueDescription
text

Button label

onPress

Callback function when button pressed

style

Button style

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - StyleSheet, - View, - Text, - TouchableHighlight, - AlertIOS, -} = ReactNative; - -var { SimpleAlertExampleBlock } = require('./AlertExample'); - -exports.framework = 'React'; -exports.title = 'AlertIOS'; -exports.description = 'iOS alerts and action sheets'; -exports.examples = [{ - title: 'Alerts', - render() { - return <SimpleAlertExampleBlock />; - } -}, -{ - title: 'Prompt Options', - render(): React.Element<any> { - return <PromptOptions />; - } -}, -{ - title: 'Prompt Types', - render() { - return ( - <View> - <TouchableHighlight - style={styles.wrapper} - onPress={() => AlertIOS.prompt('Plain Text Entry')}> - - <View style={styles.button}> - <Text> - plain-text - </Text> - </View> - - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => AlertIOS.prompt('Secure Text', null, null, 'secure-text')}> - - <View style={styles.button}> - <Text> - secure-text - </Text> - </View> - - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => AlertIOS.prompt('Login & Password', null, null, 'login-password')}> - - <View style={styles.button}> - <Text> - login-password - </Text> - </View> - - </TouchableHighlight> - </View> - ); - } -}]; - -class PromptOptions extends React.Component { - state: any; - customButtons: Array<Object>; - - constructor(props) { - super(props); - - // $FlowFixMe this seems to be a Flow bug, `saveResponse` is defined below - this.saveResponse = this.saveResponse.bind(this); - - this.customButtons = [{ - text: 'Custom OK', - onPress: this.saveResponse - }, { - text: 'Custom Cancel', - style: 'cancel', - }]; - - this.state = { - promptValue: undefined, - }; - } - - render() { - return ( - <View> - <Text style={{marginBottom: 10}}> - <Text style={{fontWeight: 'bold'}}>Prompt value:</Text> {this.state.promptValue} - </Text> - - <TouchableHighlight - style={styles.wrapper} - onPress={() => AlertIOS.prompt('Type a value', null, this.saveResponse)}> - - <View style={styles.button}> - <Text> - prompt with title & callback - </Text> - </View> - </TouchableHighlight> - - <TouchableHighlight - style={styles.wrapper} - onPress={() => AlertIOS.prompt('Type a value', null, this.customButtons)}> - - <View style={styles.button}> - <Text> - prompt with title & custom buttons - </Text> - </View> - </TouchableHighlight> - - <TouchableHighlight - style={styles.wrapper} - onPress={() => AlertIOS.prompt('Type a phone number', null, null, 'plain-text', undefined, 'phone-pad')}> - - <View style={styles.button}> - <Text> - prompt with title & custom keyboard - </Text> - </View> - </TouchableHighlight> - - <TouchableHighlight - style={styles.wrapper} - onPress={() => AlertIOS.prompt('Type a value', null, this.saveResponse, undefined, 'Default value')}> - - <View style={styles.button}> - <Text> - prompt with title, callback & default value - </Text> - </View> - </TouchableHighlight> - - <TouchableHighlight - style={styles.wrapper} - onPress={() => AlertIOS.prompt('Type a value', null, this.customButtons, 'login-password', 'admin@site.com')}> - - <View style={styles.button}> - <Text> - prompt with title, custom buttons, login/password & default value - </Text> - </View> - </TouchableHighlight> - </View> - ); - } - - saveResponse(promptValue) { - this.setState({ promptValue: JSON.stringify(promptValue) }); - } -} - -var styles = StyleSheet.create({ - wrapper: { - borderRadius: 5, - marginBottom: 5, - }, - button: { - backgroundColor: '#eeeeee', - padding: 10, - }, -});
\ No newline at end of file + \ No newline at end of file diff --git a/docs/android-building-from-source.html b/docs/android-building-from-source.html index 592638684b3..ba1d4435071 100644 --- a/docs/android-building-from-source.html +++ b/docs/android-building-from-source.html @@ -1,4 +1,4 @@ -Building React Native from source

Building React Native from source #

You will need to build React Native from source if you want to work on a new feature/bug fix, try out the latest features which are not released yet, or maintain your own fork with patches that cannot be merged to the core.

Prerequisites #

Assuming you have the Android SDK installed, run android to open the Android SDK Manager.

Make sure you have the following installed:

  1. Android SDK version 23 (compileSdkVersion in build.gradle)
  2. SDK build tools version 23.0.1 (buildToolsVersion in build.gradle)
  3. Android Support Repository >= 17 (for Android Support Library)
  4. Android NDK (download links and installation instructions below)

Point Gradle to your Android SDK: #

Step 1: Set environment variables through your local shell.

Note: Files may vary based on shell flavor. See below for examples from common shells.

  • bash: .bash_profile or .bashrc
  • zsh: .zprofile or .zshrc
  • ksh: .profile or $ENV

Example:

export ANDROID_SDK=/Users/your_unix_name/android-sdk-macosx +Building React Native from source

Building React Native from source #

You will need to build React Native from source if you want to work on a new feature/bug fix, try out the latest features which are not released yet, or maintain your own fork with patches that cannot be merged to the core.

Prerequisites #

Assuming you have the Android SDK installed, run android to open the Android SDK Manager.

Make sure you have the following installed:

  1. Android SDK version 23 (compileSdkVersion in build.gradle)
  2. SDK build tools version 23.0.1 (buildToolsVersion in build.gradle)
  3. Android Support Repository >= 17 (for Android Support Library)
  4. Android NDK (download links and installation instructions below)

Point Gradle to your Android SDK: #

Step 1: Set environment variables through your local shell.

Note: Files may vary based on shell flavor. See below for examples from common shells.

  • bash: .bash_profile or .bashrc
  • zsh: .zprofile or .zshrc
  • ksh: .profile or $ENV

Example:

export ANDROID_SDK=/Users/your_unix_name/android-sdk-macosx export ANDROID_NDK=/Users/your_unix_name/android-ndk/android-ndk-r10e

Step 2: Create a local.properties file in the android directory of your react-native app with the following contents:

Example:

sdk.dir=/Users/your_unix_name/android-sdk-macosx ndk.dir=/Users/your_unix_name/android-ndk/android-ndk-r10e

Download links for Android NDK #

  1. Mac OS (64-bit) - http://dl.google.com/android/repository/android-ndk-r10e-darwin-x86_64.zip
  2. Linux (64-bit) - http://dl.google.com/android/repository/android-ndk-r10e-linux-x86_64.zip
  3. Windows (64-bit) - http://dl.google.com/android/repository/android-ndk-r10e-windows-x86_64.zip
  4. Windows (32-bit) - http://dl.google.com/android/repository/android-ndk-r10e-windows-x86.zip

You can find further instructions on the official page.

Building the source #

1. Installing the fork #

First, you need to install react-native from your fork. For example, to install the master branch from the official repo, run the following:

npm install --save github:facebook/react-native#master

Alternatively, you can clone the repo to your node_modules directory and run npm install inside the cloned repo.

2. Adding gradle dependencies #

Add gradle-download-task as dependency in android/build.gradle:

... dependencies { @@ -44,6 +44,6 @@ dependencies { apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/animated.html b/docs/animated.html index 24db1a54fdc..f00d714f21b 100644 --- a/docs/animated.html +++ b/docs/animated.html @@ -1,4 +1,4 @@ -Animated

Animated #

The Animated library is designed to make animations fluid, powerful, and +Animated

Animated #

The Animated library is designed to make animations fluid, powerful, and easy to build and maintain. Animated focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and simple start/stop methods to control time-based animation execution.

The simplest workflow for creating an animation is to to create an @@ -144,227 +144,7 @@ API to normal Animated.Value, but multiplexed. Contains two regula } }

Methods #

constructor(valueIn?) #

setValue(value) #

setOffset(offset) #

flattenOffset() #

extractOffset() #

resetAnimation(callback?) #

stopAnimation(callback?) #

addListener(callback) #

removeListener(id) #

removeAllListeners() #

getLayout() #

Converts {x, y} into {left, top} for use in style, e.g.

style={this.state.anim.getLayout()}

getTranslateTransform() #

Converts {x, y} into a useable translation transform, e.g.

style={{ transform: this.state.anim.getTranslateTransform() - }}

class AnimatedInterpolation #

    Methods #

    constructor(parent, config) #

    interpolate(config) #

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - Animated, - Easing, - StyleSheet, - Text, - View, -} = ReactNative; -var UIExplorerButton = require('./UIExplorerButton'); - -exports.framework = 'React'; -exports.title = 'Animated - Examples'; -exports.description = 'Animated provides a powerful ' + - 'and easy-to-use API for building modern, ' + - 'interactive user experiences.'; - -exports.examples = [ - { - title: 'FadeInView', - description: 'Uses a simple timing animation to ' + - 'bring opacity from 0 to 1 when the component ' + - 'mounts.', - render: function() { - class FadeInView extends React.Component { - state: any; - - constructor(props) { - super(props); - this.state = { - fadeAnim: new Animated.Value(0), // opacity 0 - }; - } - componentDidMount() { - Animated.timing( // Uses easing functions - this.state.fadeAnim, // The value to drive - { - toValue: 1, // Target - duration: 2000, // Configuration - }, - ).start(); // Don't forget start! - } - render() { - return ( - <Animated.View // Special animatable View - style={{ - opacity: this.state.fadeAnim, // Binds - }}> - {this.props.children} - </Animated.View> - ); - } - } - class FadeInExample extends React.Component { - state: any; - - constructor(props) { - super(props); - this.state = { - show: true, - }; - } - render() { - return ( - <View> - <UIExplorerButton onPress={() => { - this.setState((state) => ( - {show: !state.show} - )); - }}> - Press to {this.state.show ? - 'Hide' : 'Show'} - </UIExplorerButton> - {this.state.show && <FadeInView> - <View style={styles.content}> - <Text>FadeInView</Text> - </View> - </FadeInView>} - </View> - ); - } - } - return <FadeInExample />; - }, - }, - { - title: 'Transform Bounce', - description: 'One `Animated.Value` is driven by a ' + - 'spring with custom constants and mapped to an ' + - 'ordered set of transforms. Each transform has ' + - 'an interpolation to convert the value into the ' + - 'right range and units.', - render: function() { - this.anim = this.anim || new Animated.Value(0); - return ( - <View> - <UIExplorerButton onPress={() => { - Animated.spring(this.anim, { - toValue: 0, // Returns to the start - velocity: 3, // Velocity makes it move - tension: -10, // Slow - friction: 1, // Oscillate a lot - }).start(); }}> - Press to Fling it! - </UIExplorerButton> - <Animated.View - style={[styles.content, { - transform: [ // Array order matters - {scale: this.anim.interpolate({ - inputRange: [0, 1], - outputRange: [1, 4], - })}, - {translateX: this.anim.interpolate({ - inputRange: [0, 1], - outputRange: [0, 500], - })}, - {rotate: this.anim.interpolate({ - inputRange: [0, 1], - outputRange: [ - '0deg', '360deg' // 'deg' or 'rad' - ], - })}, - ]} - ]}> - <Text>Transforms!</Text> - </Animated.View> - </View> - ); - }, - }, - { - title: 'Composite Animations with Easing', - description: 'Sequence, parallel, delay, and ' + - 'stagger with different easing functions.', - render: function() { - this.anims = this.anims || [1,2,3].map( - () => new Animated.Value(0) - ); - return ( - <View> - <UIExplorerButton onPress={() => { - var timing = Animated.timing; - Animated.sequence([ // One after the other - timing(this.anims[0], { - toValue: 200, - easing: Easing.linear, - }), - Animated.delay(400), // Use with sequence - timing(this.anims[0], { - toValue: 0, - easing: Easing.elastic(2), // Springy - }), - Animated.delay(400), - Animated.stagger(200, - this.anims.map((anim) => timing( - anim, {toValue: 200} - )).concat( - this.anims.map((anim) => timing( - anim, {toValue: 0} - ))), - ), - Animated.delay(400), - Animated.parallel([ - Easing.inOut(Easing.quad), // Symmetric - Easing.back(1.5), // Goes backwards first - Easing.ease // Default bezier - ].map((easing, ii) => ( - timing(this.anims[ii], { - toValue: 320, easing, duration: 3000, - }) - ))), - Animated.delay(400), - Animated.stagger(200, - this.anims.map((anim) => timing(anim, { - toValue: 0, - easing: Easing.bounce, // Like a ball - duration: 2000, - })), - ), - ]).start(); }}> - Press to Animate - </UIExplorerButton> - {['Composite', 'Easing', 'Animations!'].map( - (text, ii) => ( - <Animated.View - key={text} - style={[styles.content, { - left: this.anims[ii] - }]}> - <Text>{text}</Text> - </Animated.View> - ) - )} - </View> - ); - }, - }, - { - title: 'Continuous Interactions', - description: 'Gesture events, chaining, 2D ' + - 'values, interrupting and transitioning ' + - 'animations, etc.', - render: () => ( - <Text>Checkout the Gratuitous Animation App!</Text> - ), - } -]; - -var styles = StyleSheet.create({ - content: { - backgroundColor: 'deepskyblue', - borderWidth: 1, - borderColor: 'dodgerblue', - padding: 20, - margin: 20, - borderRadius: 10, - alignItems: 'center', - }, -});
\ No newline at end of file + \ No newline at end of file diff --git a/docs/animations.html b/docs/animations.html index c0ec3e2a949..ad0b5eea99d 100644 --- a/docs/animations.html +++ b/docs/animations.html @@ -1,36 +1,35 @@ -Animations

Animations #

Animations are very important to create a great user experience. +Animations

Animations #

Animations are very important to create a great user experience. Stationary objects must overcome inertia as they start moving. Objects in motion have momentum and rarely come to a stop immediately. Animations allow you to convey physically believable motion in your interface.

React Native provides two complementary animation systems: Animated for granular and interactive control of specific values, and LayoutAnimation for animated global layout transactions.

Animated API #

The Animated API is designed to make it very easy to concisely express a wide variety of interesting animation and interaction patterns in a very performant way. -Animated focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and simple start/stop methods to control time-based animation execution.

Animated exports four animatable component types: View, Text, Image, and ScrollView, but you can also create your own using Animated.createAnimatedComponent().

For example, a container view that fades in when it is mounted may look like this:

// FadeInView.js -import React, { Component } from 'react'; -import { - Animated, -} from 'react-native'; +Animated focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and simple start/stop methods to control time-based animation execution.

Animated exports four animatable component types: View, Text, Image, and ScrollView, but you can also create your own using Animated.createAnimatedComponent().

For example, a container view that fades in when it is mounted may look like this:

Let's break down what's happening here. In the FadeInView constructor, a new Animated.Value called fadeAnim is initialized as part of state. The opacity property on the View is mapped to this animated value. Behind the scenes, the numeric value is extracted and used to set opacity.

When the component mounts, the opacity is set to 0. @@ -182,13 +186,13 @@ the animation will always run a frame behind the gesture due to the async nature )} > {content} -</Animated.ScrollView>

You can see the native driver in action by running the UIExplorer sample app, +</Animated.ScrollView>

You can see the native driver in action by running the RNTester app, then loading the Native Animated Example. -You can also take a look at the source code to learn how these examples were produced.

Caveats #

Not everything you can do with Animated is currently supported by the native driver. +You can also take a look at the source code to learn how these examples were produced.

Caveats #

Not everything you can do with Animated is currently supported by the native driver. The main limitation is that you can only animate non-layout properties: things like transform, opacity and backgroundColor will work, but flexbox and position properties will not. When using Animated.event, it will only work with direct events and not bubbling events. -This means it does not work with PanResponder but does work with things like ScrollView#onScroll.

Additional examples #

The UIExplorer sample app has various examples of Animated in use:

LayoutAnimation API #

LayoutAnimation allows you to globally configure create and update +This means it does not work with PanResponder but does work with things like ScrollView#onScroll.

Additional examples #

The RNTester app has various examples of Animated in use:

LayoutAnimation API #

LayoutAnimation allows you to globally configure create and update animations that will be used for all views in the next render/layout cycle. This is useful for doing flexbox layout updates without bothering to measure or calculate specific properties in order to animate them directly, and is @@ -198,19 +202,28 @@ row below which would otherwise require explicit coordination between the components in order to animate them all in sync.

Note that although LayoutAnimation is very powerful and can be quite useful, it provides much less control than Animated and other animation libraries, so you may need to use another approach if you can't get LayoutAnimation to do -what you want.

Note that in order to get this to work on Android you need to set the following flags via UIManager:

UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true);

class App extends React.Component { - constructor(props) { - super(props); - this.state = { w: 100, h: 100 }; - this._onPress = this._onPress.bind(this); - } +what you want.

Note that in order to get this to work on Android you need to set the following flags via UIManager:

UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true);

This example uses a preset value, you can customize the animations as you need, see LayoutAnimation.js for more information.

Additional notes #

requestAnimationFrame #

requestAnimationFrame is a polyfill from the browser that you might be familiar with. It accepts a function as its only argument and calls that @@ -241,41 +277,15 @@ components (components that are actually backed by native views, unlike composite components) directly, without having to setState and re-render the component hierarchy.

We could use this in the Rebound example to update the scale - this might be helpful if the component that we are updating is deeply nested -and hasn't been optimized with shouldComponentUpdate.

// Back inside of the App component, replace the scrollSpring listener -// in componentWillMount with this: -this._scrollSpring.addListener({ - onSpringUpdate: () => { - if (!this._photo) { return } - var v = this._scrollSpring.getCurrentValue(); - var newProps = {style: {transform: [{scaleX: v}, {scaleY: v}]}}; - this._photo.setNativeProps(newProps); - }, -}); - -// Lastly, we update the render function to no longer pass in the -// transform via style (avoid clashes when re-rendering) and to set the -// photo ref -render() { - return ( - <View style={styles.container}> - <TouchableWithoutFeedback onPressIn={this._onPressIn} onPressOut={this._onPressOut}> - <Image ref={component => this._photo = component} - source={{uri: "img/ReboundExample.png"}} - style={{width: 250, height: 200}} /> - </TouchableWithoutFeedback> - </View> - ); -}

Run this example

It would not make sense to use setNativeProps with react-tween-state -because the updated tween values are set on the state automatically by -the library - Rebound on the other hand gives us an updated value for -each frame with the onSpringUpdate function.

If you find your animations with dropping frames (performing below 60 -frames per second), look into using setNativeProps or -shouldComponentUpdate to optimize them. You may also want to defer any -computationally intensive work until after animations are complete, -using the -InteractionManager. You -can monitor the frame rate by using the In-App Developer Menu "FPS -Monitor" tool.

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file + \ No newline at end of file diff --git a/docs/appregistry.html b/docs/appregistry.html index 2399c36dd4d..0b20554d382 100644 --- a/docs/appregistry.html +++ b/docs/appregistry.html @@ -1,4 +1,15 @@ -AppRegistry

AppRegistry #

AppRegistry is the JS entry point to running all React Native apps. App +AppRegistry

AppRegistry #

+ +

AppRegistry is the JS entry point to running all React Native apps. App root components should register themselves with AppRegistry.registerComponent, then the native system can load the bundle for the app and then actually run the app when it's ready by invoking @@ -6,7 +17,7 @@ for the app and then actually run the app when it's ready by invoking AppRegistry.unmountApplicationComponentAtRootTag with the tag that was passed into runApplication. These should always be used as a pair.

AppRegistry should be required early in the require sequence to make sure the JS execution environment is setup before other modules are -required.

Methods #

static registerConfig(config) #

static registerComponent(appKey, component, section?) #

static registerRunnable(appKey, run) #

static registerSection(appKey, component) #

static getAppKeys() #

static getSectionKeys() #

static getSections() #

static getRunnable(appKey) #

static getRegistry() #

static setComponentProviderInstrumentationHook(hook) #

static runApplication(appKey, appParameters) #

static unmountApplicationComponentAtRootTag(rootTag) #

static registerHeadlessTask(taskKey, task) #

Register a headless task. A headless task is a bit of code that runs without a UI. +required.

Methods #

static registerConfig(config) #

static registerComponent(appKey, componentProvider, section?) #

static registerRunnable(appKey, run) #

static registerSection(appKey, component) #

static getAppKeys() #

static getSectionKeys() #

static getSections() #

static getRunnable(appKey) #

static getRegistry() #

static setComponentProviderInstrumentationHook(hook) #

static runApplication(appKey, appParameters) #

static unmountApplicationComponentAtRootTag(rootTag) #

static registerHeadlessTask(taskKey, task) #

Register a headless task. A headless task is a bit of code that runs without a UI. @param taskKey the key associated with this task @param task a promise returning function that takes some data passed from the native side as the only argument; when the promise is resolved or rejected the native side is @@ -28,6 +39,6 @@ sure the JS execution environment is setup before other modules are apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/appstate.html b/docs/appstate.html index 67c152da096..4c78200b1e8 100644 --- a/docs/appstate.html +++ b/docs/appstate.html @@ -1,4 +1,4 @@ -AppState

AppState #

AppState can tell you if the app is in the foreground or background, +AppState

AppState #

AppState can tell you if the app is in the foreground or background, and notify you when the state changes.

AppState is frequently used to determine the intent and proper behavior when handling push notifications.

App States #

  • active - The app is running in the foreground
  • background - The app is running in the background. The user is either in another app or on the home screen
  • inactive - This is a state that occurs when transitioning between @@ -43,93 +43,7 @@ and providing the handler

    TODO: now that AppState is a subclass of NativeE addEventListener and removeEventListener and just use addListener and listener.remove() directly. That will be a breaking change though, as both the method and event names are different (addListener events are currently -required to be globally unique).

removeEventListener(type, handler) #

Remove a handler by passing the change event type and the handler

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -const React = require('react'); -const ReactNative = require('react-native'); -const { - AppState, - Text, - View -} = ReactNative; - -class AppStateSubscription extends React.Component { - state = { - appState: AppState.currentState, - previousAppStates: [], - memoryWarnings: 0, - }; - - componentDidMount() { - AppState.addEventListener('change', this._handleAppStateChange); - AppState.addEventListener('memoryWarning', this._handleMemoryWarning); - } - - componentWillUnmount() { - AppState.removeEventListener('change', this._handleAppStateChange); - AppState.removeEventListener('memoryWarning', this._handleMemoryWarning); - } - - _handleMemoryWarning = () => { - this.setState({memoryWarnings: this.state.memoryWarnings + 1}); - }; - - _handleAppStateChange = (appState) => { - var previousAppStates = this.state.previousAppStates.slice(); - previousAppStates.push(this.state.appState); - this.setState({ - appState, - previousAppStates, - }); - }; - - render() { - if (this.props.showMemoryWarnings) { - return ( - <View> - <Text>{this.state.memoryWarnings}</Text> - </View> - ); - } - if (this.props.showCurrentOnly) { - return ( - <View> - <Text>{this.state.appState}</Text> - </View> - ); - } - return ( - <View> - <Text>{JSON.stringify(this.state.previousAppStates)}</Text> - </View> - ); - } -} - -exports.title = 'AppState'; -exports.description = 'app background status'; -exports.examples = [ - { - title: 'AppState.currentState', - description: 'Can be null on app initialization', - render() { return <Text>{AppState.currentState}</Text>; } - }, - { - title: 'Subscribed AppState:', - description: 'This changes according to the current state, so you can only ever see it rendered as "active"', - render(): React.Element<any> { return <AppStateSubscription showCurrentOnly={true} />; } - }, - { - title: 'Previous states:', - render(): React.Element<any> { return <AppStateSubscription showCurrentOnly={false} />; } - }, - { - platform: 'ios', - title: 'Memory Warnings', - description: 'In the IOS simulator, hit Shift+Command+M to simulate a memory warning.', - render(): React.Element<any> { return <AppStateSubscription showMemoryWarnings={true} />; } - }, -];
\ No newline at end of file + \ No newline at end of file diff --git a/docs/asyncstorage.html b/docs/asyncstorage.html index a29d694b35c..c801f35ced9 100644 --- a/docs/asyncstorage.html +++ b/docs/asyncstorage.html @@ -1,4 +1,4 @@ -AsyncStorage

AsyncStorage #

AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage +AsyncStorage

AsyncStorage #

AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.

It is recommended that you use an abstraction on top of AsyncStorage instead of AsyncStorage directly for anything more than light usage since it operates globally.

On iOS, AsyncStorage is backed by native code that stores small values in a @@ -115,109 +115,7 @@ AsyncStorage. // Console log results: // => UID234 {"name":"Chris","age":31,"traits":{"shoe_size":10,"hair":"brown","eyes":"blue"}} -// => UID345 {"name":"Marge","age":26,"traits":{"shoe_size":6,"hair":"blonde","eyes":"green"}}

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - AsyncStorage, - PickerIOS, - Text, - View -} = ReactNative; -var PickerItemIOS = PickerIOS.Item; - -var STORAGE_KEY = '@AsyncStorageExample:key'; -var COLORS = ['red', 'orange', 'yellow', 'green', 'blue']; - -class BasicStorageExample extends React.Component { - state = { - selectedValue: COLORS[0], - messages: [], - }; - - componentDidMount() { - this._loadInitialState().done(); - } - - _loadInitialState = async () => { - try { - var value = await AsyncStorage.getItem(STORAGE_KEY); - if (value !== null){ - this.setState({selectedValue: value}); - this._appendMessage('Recovered selection from disk: ' + value); - } else { - this._appendMessage('Initialized with no selection on disk.'); - } - } catch (error) { - this._appendMessage('AsyncStorage error: ' + error.message); - } - }; - - render() { - var color = this.state.selectedValue; - return ( - <View> - <PickerIOS - selectedValue={color} - onValueChange={this._onValueChange}> - {COLORS.map((value) => ( - <PickerItemIOS - key={value} - value={value} - label={value} - /> - ))} - </PickerIOS> - <Text> - {'Selected: '} - <Text style={{color}}> - {this.state.selectedValue} - </Text> - </Text> - <Text>{' '}</Text> - <Text onPress={this._removeStorage}> - Press here to remove from storage. - </Text> - <Text>{' '}</Text> - <Text>Messages:</Text> - {this.state.messages.map((m) => <Text key={m}>{m}</Text>)} - </View> - ); - } - - _onValueChange = async (selectedValue) => { - this.setState({selectedValue}); - try { - await AsyncStorage.setItem(STORAGE_KEY, selectedValue); - this._appendMessage('Saved selection to disk: ' + selectedValue); - } catch (error) { - this._appendMessage('AsyncStorage error: ' + error.message); - } - }; - - _removeStorage = async () => { - try { - await AsyncStorage.removeItem(STORAGE_KEY); - this._appendMessage('Selection removed from disk.'); - } catch (error) { - this._appendMessage('AsyncStorage error: ' + error.message); - } - }; - - _appendMessage = (message) => { - this.setState({messages: this.state.messages.concat(message)}); - }; -} - -exports.title = 'AsyncStorage'; -exports.description = 'Asynchronous local disk storage.'; -exports.examples = [ - { - title: 'Basics - getItem, setItem, removeItem', - render(): React.Element<any> { return <BasicStorageExample />; } - }, -];
\ No newline at end of file + \ No newline at end of file diff --git a/docs/backandroid.html b/docs/backandroid.html index 9bd37022ec4..a1ec5335469 100644 --- a/docs/backandroid.html +++ b/docs/backandroid.html @@ -1,4 +1,4 @@ -BackAndroid

BackAndroid #

Deprecated. Use BackHandler instead.

Methods #

static exitApp() #

static addEventListener(eventName, handler) #

static removeEventListener(eventName, handler) #

You can edit the content above on GitHub and send us a pull request!

BackAndroid #

Deprecated. Use BackHandler instead.

Methods #

static exitApp() #

static addEventListener(eventName, handler) #

static removeEventListener(eventName, handler) #

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file + \ No newline at end of file diff --git a/docs/backhandler.html b/docs/backhandler.html index fb400cb6df6..059340a1d77 100644 --- a/docs/backhandler.html +++ b/docs/backhandler.html @@ -1,4 +1,4 @@ -BackHandler

BackHandler #

Detect hardware button presses for back navigation.

Android: Detect hardware back button presses, and programmatically invoke the default back button +BackHandler

BackHandler #

Detect hardware button presses for back navigation.

Android: Detect hardware back button presses, and programmatically invoke the default back button functionality to exit the app if there are no listeners or if none of the listeners return true.

tvOS: Detect presses of the menu button on the TV remote. (Still to be implemented: programmatically disable menu button handling functionality to exit the app if there are no listeners or if none of the listeners return true.)

iOS: Not applicable.

The event subscriptions are called in reverse order (i.e. last registered subscription first), @@ -27,6 +27,6 @@ and if one subscription returns true then subscriptions registered earlier will apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/building-for-apple-tv.html b/docs/building-for-apple-tv.html new file mode 100644 index 00000000000..1e8af6a2fcf --- /dev/null +++ b/docs/building-for-apple-tv.html @@ -0,0 +1,59 @@ +Building For Apple TV

Building For Apple TV #

Apple TV support has been implemented with the intention of making existing React Native iOS applications "just work" on tvOS, with few or no changes needed in the JavaScript code for the applications.

The RNTester app supports Apple TV; use the RNTester-tvOS build target to build for tvOS.

Build changes #

  • Native layer: React Native Xcode projects all now have Apple TV build targets, with names ending in the string '-tvOS'.

  • react-native init: New React Native projects created with react-native init will have Apple TV target automatically created in their XCode projects.

  • JavaScript layer: Support for Apple TV has been added to Platform.ios.js. You can check whether code is running on AppleTV by doing

var Platform = require('Platform'); +var running_on_apple_tv = Platform.isTVOS;

Code changes #

  • General support for tvOS: Apple TV specific changes in native code are all wrapped by the TARGET_OS_TV define. These include changes to suppress APIs that are not supported on tvOS (e.g. web views, sliders, switches, status bar, etc.), and changes to support user input from the TV remote or keyboard.

  • Common codebase: Since tvOS and iOS share most Objective-C and JavaScript code in common, most documentation for iOS applies equally to tvOS.

  • Access to touchable controls: When running on Apple TV, the native view class is RCTTVView, which has additional methods to make use of the tvOS focus engine. The Touchable mixin has code added to detect focus changes and use existing methods to style the components properly and initiate the proper actions when the view is selected using the TV remote, so TouchableHighlight and TouchableOpacity will "just work". In particular:

    • touchableHandleActivePressIn will be executed when the touchable view goes into focus
    • touchableHandleActivePressOut will be executed when the touchable view goes out of focus
    • touchableHandlePress will be executed when the touchable view is actually selected by pressing the "select" button on the TV remote.
  • TV remote/keyboard input: A new native class, RCTTVRemoteHandler, sets up gesture recognizers for TV remote events. When TV remote events occur, this class fires notifications that are picked up by RCTTVNavigationEventEmitter (a subclass of RCTEventEmitter), that fires a JS event. This event will be picked up by instances of the TVEventHandler JavaScript object. Application code that needs to implement custom handling of TV remote events can create an instance of TVEventHandler and listen for these events, as in the following code:

var TVEventHandler = require('TVEventHandler'); + +. +. +. + +class Game2048 extends React.Component { + _tvEventHandler: any; + + _enableTVEventHandler() { + this._tvEventHandler = new TVEventHandler(); + this._tvEventHandler.enable(this, function(cmp, evt) { + if (evt && evt.eventType === 'right') { + cmp.setState({board: cmp.state.board.move(2)}); + } else if(evt && evt.eventType === 'up') { + cmp.setState({board: cmp.state.board.move(1)}); + } else if(evt && evt.eventType === 'left') { + cmp.setState({board: cmp.state.board.move(0)}); + } else if(evt && evt.eventType === 'down') { + cmp.setState({board: cmp.state.board.move(3)}); + } else if(evt && evt.eventType === 'playPause') { + cmp.restartGame(); + } + }); + } + + _disableTVEventHandler() { + if (this._tvEventHandler) { + this._tvEventHandler.disable(); + delete this._tvEventHandler; + } + } + + componentDidMount() { + this._enableTVEventHandler(); + } + + componentWillUnmount() { + this._disableTVEventHandler(); + }
  • TV remote animations: RCTTVView native code implements Apple-recommended parallax animations to help guide the eye as the user navigates through views. The animations can be disabled or adjusted with new optional view properties.

  • Back navigation with the TV remote menu button: The BackHandler component, originally written to support the Android back button, now also supports back navigation on the Apple TV using the menu button on the TV remote.

  • Known issues:

    • ListView scrolling. The issue can be easily worked around by setting removeClippedSubviews to false in ListView and similar components. For more discussion of this issue, see this PR.

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file diff --git a/docs/button.html b/docs/button.html index 5b1e7dc258c..949c74f7c0a 100644 --- a/docs/button.html +++ b/docs/button.html @@ -1,4 +1,4 @@ -Button

Button #

A basic button component that should render nicely on any platform. Supports +Button

Button #

A basic button component that should render nicely on any platform. Supports a minimal level of customization.

If this button doesn't look right for your app, you can build your own @@ -10,94 +10,7 @@ Or, take a look at the ="Learn More" color="#841584" accessibilityLabel="Learn more about this purple button" -/>

Props #

accessibilityLabel?: ?string #

Text to display for blindness accessibility features

color?: ?string #

Color of the text (iOS), or background color of the button (Android)

disabled?: ?boolean #

If true, disable all interactions for this component.

onPress: () => any #

Handler to be called when the user taps the button

testID?: ?string #

Used to locate this view in end-to-end tests.

title: string #

Text to display inside the button

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -const React = require('react'); -const ReactNative = require('react-native'); -const { - Alert, - Button, - View, -} = ReactNative; - -const onButtonPress = () => { - Alert.alert('Button has been pressed!'); -}; - -exports.displayName = 'ButtonExample'; -exports.framework = 'React'; -exports.title = '<Button>'; -exports.description = 'Simple React Native button component.'; - -exports.examples = [ - { - title: 'Simple Button', - description: 'The title and onPress handler are required. It is ' + - 'recommended to set accessibilityLabel to help make your app usable by ' + - 'everyone.', - render: function() { - return ( - <Button - onPress={onButtonPress} - title="Press Me" - accessibilityLabel="See an informative alert" - /> - ); - }, - }, - { - title: 'Adjusted color', - description: 'Adjusts the color in a way that looks standard on each ' + - 'platform. On iOS, the color prop controls the color of the text. On ' + - 'Android, the color adjusts the background color of the button.', - render: function() { - return ( - <Button - onPress={onButtonPress} - title="Press Purple" - color="#841584" - accessibilityLabel="Learn more about purple" - /> - ); - }, - }, - { - title: 'Fit to text layout', - description: 'This layout strategy lets the title define the width of ' + - 'the button', - render: function() { - return ( - <View style={{flexDirection: 'row', justifyContent: 'space-between'}}> - <Button - onPress={onButtonPress} - title="This looks great!" - accessibilityLabel="This sounds great!" - /> - <Button - onPress={onButtonPress} - title="Ok!" - color="#841584" - accessibilityLabel="Ok, Great!" - /> - </View> - ); - }, - }, - { - title: 'Disabled Button', - description: 'All interactions for the component are disabled.', - render: function() { - return ( - <Button - disabled - onPress={onButtonPress} - title="I Am Disabled" - accessibilityLabel="See an informative alert" - /> - ); - }, - }, -];
\ No newline at end of file + \ No newline at end of file diff --git a/docs/cameraroll.html b/docs/cameraroll.html index 62307b9b643..e26642f657b 100644 --- a/docs/cameraroll.html +++ b/docs/cameraroll.html @@ -1,137 +1,12 @@ -CameraRoll

CameraRoll #

CameraRoll provides access to the local camera roll / gallery. +CameraRoll

CameraRoll #

CameraRoll provides access to the local camera roll / gallery. Before using this you must link the RCTCameraRoll library. You can refer to Linking for help.

Permissions #

The user's permission is required in order to access the Camera Roll on devices running iOS 10 or later. -Fill out the NSCameraUsageDescription key in your Info.plist with a string that describes how your -app will use this data. This key will appear as Privacy - Camera Usage Description in Xcode.

Methods #

static saveImageWithTag(tag) #

static saveToCameraRoll(tag, type?) #

Saves the photo or video to the camera roll / gallery.

On Android, the tag must be a local image or video URI, such as "file:///sdcard/img.png".

On iOS, the tag can be any image URI (including local, remote asset-library and base64 data URIs) +Add the NSPhotoLibraryUsageDescription key in your Info.plist with a string that describes how your +app will use this data. This key will appear as Privacy - Photo Library Usage Description in Xcode.

Methods #

=(;, AssetTypeOptions, static, (, :) #

static saveToCameraRoll(tag, type?) #

Saves the photo or video to the camera roll / gallery.

On Android, the tag must be a local image or video URI, such as "file:///sdcard/img.png".

On iOS, the tag can be any image URI (including local, remote asset-library and base64 data URIs) or a local video file URI (remote or data URIs are not supported for saving video at this time).

If the tag has a file extension of .mov or .mp4, it will be inferred as a video. Otherwise it will be treated as a photo. To override the automatic choice, you can pass an optional type parameter that must be one of 'photo' or 'video'.

Returns a Promise which will resolve with the new URI.

static getPhotos(params) #

Returns a Promise with photo identifier objects from the local camera -roll of the device matching shape defined by getPhotosReturnChecker.

Expects a params object of the following shape:

  • first : {number} : The number of photos wanted in reverse order of the photo application (i.e. most recent first for SavedPhotos).
  • after : {string} : A cursor that matches page_info { end_cursor } returned from a previous call to getPhotos.
  • groupTypes : {string} : Specifies which group types to filter the results to. Valid values are:
    • Album
    • All
    • Event
    • Faces
    • Library
    • PhotoStream
    • SavedPhotos // default
  • groupName : {string} : Specifies filter on group names, like 'Recent Photos' or custom album titles.
  • assetType : {string} : Specifies filter on asset type. Valid values are:
    • All
    • Videos
    • Photos // default
  • mimeTypes : {string} : Filter by mimetype (e.g. image/jpeg).

Returns a Promise which when resolved will be of the following shape:

  • edges : {Array<node>} An array of node objects
    • node: {object} An object with the following shape:
      • type: {string}
      • group_name: {string}
      • image: {object} : An object with the following shape:
        • uri: {string}
        • height: {number}
        • width: {number}
        • isStored: {boolean}
      • timestamp: {number}
      • location: {object} : An object with the following shape:
        • latitude: {number}
        • longitude: {number}
        • altitude: {number}
        • heading: {number}
        • speed: {number}
  • page_info : {object} : An object with the following shape:
    • has_next_page: {boolean}
    • start_cursor: {boolean}
    • end_cursor: {boolean}

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -const React = require('react'); -const ReactNative = require('react-native'); -const { - CameraRoll, - Image, - Slider, - StyleSheet, - Switch, - Text, - View, - TouchableOpacity -} = ReactNative; - -const invariant = require('fbjs/lib/invariant'); - -const CameraRollView = require('./CameraRollView'); - -const AssetScaledImageExampleView = require('./AssetScaledImageExample'); - -class CameraRollExample extends React.Component { - state = { - groupTypes: 'SavedPhotos', - sliderValue: 1, - bigImages: true, - }; - _cameraRollView: ?CameraRollView; - render() { - return ( - <View> - <Switch - onValueChange={this._onSwitchChange} - value={this.state.bigImages} - /> - <Text>{(this.state.bigImages ? 'Big' : 'Small') + ' Images'}</Text> - <Slider - value={this.state.sliderValue} - onValueChange={this._onSliderChange} - /> - <Text>{'Group Type: ' + this.state.groupTypes}</Text> - <CameraRollView - ref={(ref) => { this._cameraRollView = ref; }} - batchSize={20} - groupTypes={this.state.groupTypes} - renderImage={this._renderImage} - /> - </View> - ); - } - - loadAsset = (asset) => { - if (this.props.navigator) { - this.props.navigator.push({ - title: 'Camera Roll Image', - component: AssetScaledImageExampleView, - backButtonTitle: 'Back', - passProps: { asset: asset }, - }); - } - }; - - _renderImage = (asset) => { - const imageSize = this.state.bigImages ? 150 : 75; - const imageStyle = [styles.image, {width: imageSize, height: imageSize}]; - const {location} = asset.node; - const locationStr = location ? JSON.stringify(location) : 'Unknown location'; - return ( - <TouchableOpacity key={asset} onPress={ this.loadAsset.bind( this, asset ) }> - <View style={styles.row}> - <Image - source={asset.node.image} - style={imageStyle} - /> - <View style={styles.info}> - <Text style={styles.url}>{asset.node.image.uri}</Text> - <Text>{locationStr}</Text> - <Text>{asset.node.group_name}</Text> - <Text>{new Date(asset.node.timestamp).toString()}</Text> - </View> - </View> - </TouchableOpacity> - ); - }; - - _onSliderChange = (value) => { - const options = CameraRoll.GroupTypesOptions; - const index = Math.floor(value * options.length * 0.99); - const groupTypes = options[index]; - if (groupTypes !== this.state.groupTypes) { - this.setState({groupTypes: groupTypes}); - } - }; - - _onSwitchChange = (value) => { - invariant(this._cameraRollView, 'ref should be set'); - this._cameraRollView.rendererChanged(); - this.setState({ bigImages: value }); - }; -} - -const styles = StyleSheet.create({ - row: { - flexDirection: 'row', - flex: 1, - }, - url: { - fontSize: 9, - marginBottom: 14, - }, - image: { - margin: 4, - }, - info: { - flex: 1, - }, -}); - -exports.title = 'Camera Roll'; -exports.description = 'Example component that uses CameraRoll to list user\'s photos'; -exports.examples = [ - { - title: 'Photos', - render(): React.Element<any> { return <CameraRollExample />; } - } -];
\ No newline at end of file + \ No newline at end of file diff --git a/docs/clipboard.html b/docs/clipboard.html index 644d86edfb6..071d2d06ff7 100644 --- a/docs/clipboard.html +++ b/docs/clipboard.html @@ -1,56 +1,8 @@ -Clipboard

Clipboard #

Clipboard gives you an interface for setting and getting content from Clipboard on both iOS and Android

Methods #

static getString() #

Get content of string type, this method returns a Promise, so you can use following code to get clipboard content

async _getContent() { +Clipboard

Clipboard #

Clipboard gives you an interface for setting and getting content from Clipboard on both iOS and Android

Methods #

static getString() #

Get content of string type, this method returns a Promise, so you can use following code to get clipboard content

async _getContent() { var content = await Clipboard.getString(); }

static setString(content) #

Set content of string type. You can use following code to set clipboard content

_setContent() { Clipboard.setString('hello world'); -}

@param the content to be stored in the clipboard.

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - Clipboard, - View, - Text, -} = ReactNative; - -class ClipboardExample extends React.Component { - state = { - content: 'Content will appear here' - }; - - _setClipboardContent = async () => { - Clipboard.setString('Hello World'); - try { - var content = await Clipboard.getString(); - this.setState({content}); - } catch (e) { - this.setState({content:e.message}); - } - }; - - render() { - return ( - <View> - <Text onPress={this._setClipboardContent} style={{color: 'blue'}}> - Tap to put "Hello World" in the clipboard - </Text> - <Text style={{color: 'red', marginTop: 20}}> - {this.state.content} - </Text> - </View> - ); - } -} - -exports.title = 'Clipboard'; -exports.description = 'Show Clipboard contents.'; -exports.examples = [ - { - title: 'Clipboard.setString() and getString()', - render() { - return <ClipboardExample/>; - } - } -];
\ No newline at end of file + \ No newline at end of file diff --git a/docs/colors.html b/docs/colors.html index 9dccc7bd31b..b6e8dbcfa0c 100644 --- a/docs/colors.html +++ b/docs/colors.html @@ -1,4 +1,4 @@ -Colors

Colors #

Components in React Native are styled using JavaScript. Color properties usually match how CSS works on the web.

Red-green-blue #

React Native supports rgb() and rgba() in both hexadecimal and functional notation:

  • '#f0f' (#rgb)
  • '#ff00ff' (#rrggbb)

  • 'rgb(255, 0, 255)'

  • 'rgba(255, 255, 255, 1.0)'

  • '#f0ff' (#rgba)

  • '#ff00ff00' (#rrggbbaa)

Hue-saturation-lightness #

hsl() and hsla() is supported in functional notation:

  • 'hsl(360, 100%, 100%)'
  • 'hsla(360, 100%, 100%, 1.0)'

transparent #

This is a shortcut for rgba(0,0,0,0):

  • 'transparent'

Named colors #

You can also use color names as values. React Native follows the CSS3 specification:

  • aliceblue (#f0f8ff)
  • antiquewhite (#faebd7)
  • aqua (#00ffff)
  • aquamarine (#7fffd4)
  • azure (#f0ffff)
  • beige (#f5f5dc)
  • bisque (#ffe4c4)
  • black (#000000)
  • blanchedalmond (#ffebcd)
  • blue (#0000ff)
  • blueviolet (#8a2be2)
  • brown (#a52a2a)
  • burlywood (#deb887)
  • cadetblue (#5f9ea0)
  • chartreuse (#7fff00)
  • chocolate (#d2691e)
  • coral (#ff7f50)
  • cornflowerblue (#6495ed)
  • cornsilk (#fff8dc)
  • crimson (#dc143c)
  • cyan (#00ffff)
  • darkblue (#00008b)
  • darkcyan (#008b8b)
  • darkgoldenrod (#b8860b)
  • darkgray (#a9a9a9)
  • darkgreen (#006400)
  • darkgrey (#a9a9a9)
  • darkkhaki (#bdb76b)
  • darkmagenta (#8b008b)
  • darkolivegreen (#556b2f)
  • darkorange (#ff8c00)
  • darkorchid (#9932cc)
  • darkred (#8b0000)
  • darksalmon (#e9967a)
  • darkseagreen (#8fbc8f)
  • darkslateblue (#483d8b)
  • darkslategray (#2f4f4f)
  • darkslategrey (#2f4f4f)
  • darkturquoise (#00ced1)
  • darkviolet (#9400d3)
  • deeppink (#ff1493)
  • deepskyblue (#00bfff)
  • dimgray (#696969)
  • dimgrey (#696969)
  • dodgerblue (#1e90ff)
  • firebrick (#b22222)
  • floralwhite (#fffaf0)
  • forestgreen (#228b22)
  • fuchsia (#ff00ff)
  • gainsboro (#dcdcdc)
  • ghostwhite (#f8f8ff)
  • gold (#ffd700)
  • goldenrod (#daa520)
  • gray (#808080)
  • green (#008000)
  • greenyellow (#adff2f)
  • grey (#808080)
  • honeydew (#f0fff0)
  • hotpink (#ff69b4)
  • indianred (#cd5c5c)
  • indigo (#4b0082)
  • ivory (#fffff0)
  • khaki (#f0e68c)
  • lavender (#e6e6fa)
  • lavenderblush (#fff0f5)
  • lawngreen (#7cfc00)
  • lemonchiffon (#fffacd)
  • lightblue (#add8e6)
  • lightcoral (#f08080)
  • lightcyan (#e0ffff)
  • lightgoldenrodyellow (#fafad2)
  • lightgray (#d3d3d3)
  • lightgreen (#90ee90)
  • lightgrey (#d3d3d3)
  • lightpink (#ffb6c1)
  • lightsalmon (#ffa07a)
  • lightseagreen (#20b2aa)
  • lightskyblue (#87cefa)
  • lightslategray (#778899)
  • lightslategrey (#778899)
  • lightsteelblue (#b0c4de)
  • lightyellow (#ffffe0)
  • lime (#00ff00)
  • limegreen (#32cd32)
  • linen (#faf0e6)
  • magenta (#ff00ff)
  • maroon (#800000)
  • mediumaquamarine (#66cdaa)
  • mediumblue (#0000cd)
  • mediumorchid (#ba55d3)
  • mediumpurple (#9370db)
  • mediumseagreen (#3cb371)
  • mediumslateblue (#7b68ee)
  • mediumspringgreen (#00fa9a)
  • mediumturquoise (#48d1cc)
  • mediumvioletred (#c71585)
  • midnightblue (#191970)
  • mintcream (#f5fffa)
  • mistyrose (#ffe4e1)
  • moccasin (#ffe4b5)
  • navajowhite (#ffdead)
  • navy (#000080)
  • oldlace (#fdf5e6)
  • olive (#808000)
  • olivedrab (#6b8e23)
  • orange (#ffa500)
  • orangered (#ff4500)
  • orchid (#da70d6)
  • palegoldenrod (#eee8aa)
  • palegreen (#98fb98)
  • paleturquoise (#afeeee)
  • palevioletred (#db7093)
  • papayawhip (#ffefd5)
  • peachpuff (#ffdab9)
  • peru (#cd853f)
  • pink (#ffc0cb)
  • plum (#dda0dd)
  • powderblue (#b0e0e6)
  • purple (#800080)
  • rebeccapurple (#663399)
  • red (#ff0000)
  • rosybrown (#bc8f8f)
  • royalblue (#4169e1)
  • saddlebrown (#8b4513)
  • salmon (#fa8072)
  • sandybrown (#f4a460)
  • seagreen (#2e8b57)
  • seashell (#fff5ee)
  • sienna (#a0522d)
  • silver (#c0c0c0)
  • skyblue (#87ceeb)
  • slateblue (#6a5acd)
  • slategray (#708090)
  • slategrey (#708090)
  • snow (#fffafa)
  • springgreen (#00ff7f)
  • steelblue (#4682b4)
  • tan (#d2b48c)
  • teal (#008080)
  • thistle (#d8bfd8)
  • tomato (#ff6347)
  • turquoise (#40e0d0)
  • violet (#ee82ee)
  • wheat (#f5deb3)
  • white (#ffffff)
  • whitesmoke (#f5f5f5)
  • yellow (#ffff00)
  • yellowgreen (#9acd32)

You can edit the content above on GitHub and send us a pull request!

Colors #

Components in React Native are styled using JavaScript. Color properties usually match how CSS works on the web.

Red-green-blue #

React Native supports rgb() and rgba() in both hexadecimal and functional notation:

  • '#f0f' (#rgb)
  • '#ff00ff' (#rrggbb)

  • 'rgb(255, 0, 255)'

  • 'rgba(255, 255, 255, 1.0)'

  • '#f0ff' (#rgba)

  • '#ff00ff00' (#rrggbbaa)

Hue-saturation-lightness #

hsl() and hsla() is supported in functional notation:

  • 'hsl(360, 100%, 100%)'
  • 'hsla(360, 100%, 100%, 1.0)'

transparent #

This is a shortcut for rgba(0,0,0,0):

  • 'transparent'

Named colors #

You can also use color names as values. React Native follows the CSS3 specification:

  • aliceblue (#f0f8ff)
  • antiquewhite (#faebd7)
  • aqua (#00ffff)
  • aquamarine (#7fffd4)
  • azure (#f0ffff)
  • beige (#f5f5dc)
  • bisque (#ffe4c4)
  • black (#000000)
  • blanchedalmond (#ffebcd)
  • blue (#0000ff)
  • blueviolet (#8a2be2)
  • brown (#a52a2a)
  • burlywood (#deb887)
  • cadetblue (#5f9ea0)
  • chartreuse (#7fff00)
  • chocolate (#d2691e)
  • coral (#ff7f50)
  • cornflowerblue (#6495ed)
  • cornsilk (#fff8dc)
  • crimson (#dc143c)
  • cyan (#00ffff)
  • darkblue (#00008b)
  • darkcyan (#008b8b)
  • darkgoldenrod (#b8860b)
  • darkgray (#a9a9a9)
  • darkgreen (#006400)
  • darkgrey (#a9a9a9)
  • darkkhaki (#bdb76b)
  • darkmagenta (#8b008b)
  • darkolivegreen (#556b2f)
  • darkorange (#ff8c00)
  • darkorchid (#9932cc)
  • darkred (#8b0000)
  • darksalmon (#e9967a)
  • darkseagreen (#8fbc8f)
  • darkslateblue (#483d8b)
  • darkslategrey (#2f4f4f)
  • darkturquoise (#00ced1)
  • darkviolet (#9400d3)
  • deeppink (#ff1493)
  • deepskyblue (#00bfff)
  • dimgray (#696969)
  • dimgrey (#696969)
  • dodgerblue (#1e90ff)
  • firebrick (#b22222)
  • floralwhite (#fffaf0)
  • forestgreen (#228b22)
  • fuchsia (#ff00ff)
  • gainsboro (#dcdcdc)
  • ghostwhite (#f8f8ff)
  • gold (#ffd700)
  • goldenrod (#daa520)
  • gray (#808080)
  • green (#008000)
  • greenyellow (#adff2f)
  • grey (#808080)
  • honeydew (#f0fff0)
  • hotpink (#ff69b4)
  • indianred (#cd5c5c)
  • indigo (#4b0082)
  • ivory (#fffff0)
  • khaki (#f0e68c)
  • lavender (#e6e6fa)
  • lavenderblush (#fff0f5)
  • lawngreen (#7cfc00)
  • lemonchiffon (#fffacd)
  • lightblue (#add8e6)
  • lightcoral (#f08080)
  • lightcyan (#e0ffff)
  • lightgoldenrodyellow (#fafad2)
  • lightgray (#d3d3d3)
  • lightgreen (#90ee90)
  • lightgrey (#d3d3d3)
  • lightpink (#ffb6c1)
  • lightsalmon (#ffa07a)
  • lightseagreen (#20b2aa)
  • lightskyblue (#87cefa)
  • lightslategrey (#778899)
  • lightsteelblue (#b0c4de)
  • lightyellow (#ffffe0)
  • lime (#00ff00)
  • limegreen (#32cd32)
  • linen (#faf0e6)
  • magenta (#ff00ff)
  • maroon (#800000)
  • mediumaquamarine (#66cdaa)
  • mediumblue (#0000cd)
  • mediumorchid (#ba55d3)
  • mediumpurple (#9370db)
  • mediumseagreen (#3cb371)
  • mediumslateblue (#7b68ee)
  • mediumspringgreen (#00fa9a)
  • mediumturquoise (#48d1cc)
  • mediumvioletred (#c71585)
  • midnightblue (#191970)
  • mintcream (#f5fffa)
  • mistyrose (#ffe4e1)
  • moccasin (#ffe4b5)
  • navajowhite (#ffdead)
  • navy (#000080)
  • oldlace (#fdf5e6)
  • olive (#808000)
  • olivedrab (#6b8e23)
  • orange (#ffa500)
  • orangered (#ff4500)
  • orchid (#da70d6)
  • palegoldenrod (#eee8aa)
  • palegreen (#98fb98)
  • paleturquoise (#afeeee)
  • palevioletred (#db7093)
  • papayawhip (#ffefd5)
  • peachpuff (#ffdab9)
  • peru (#cd853f)
  • pink (#ffc0cb)
  • plum (#dda0dd)
  • powderblue (#b0e0e6)
  • purple (#800080)
  • rebeccapurple (#663399)
  • red (#ff0000)
  • rosybrown (#bc8f8f)
  • royalblue (#4169e1)
  • saddlebrown (#8b4513)
  • salmon (#fa8072)
  • sandybrown (#f4a460)
  • seagreen (#2e8b57)
  • seashell (#fff5ee)
  • sienna (#a0522d)
  • silver (#c0c0c0)
  • skyblue (#87ceeb)
  • slateblue (#6a5acd)
  • slategray (#708090)
  • snow (#fffafa)
  • springgreen (#00ff7f)
  • steelblue (#4682b4)
  • tan (#d2b48c)
  • teal (#008080)
  • thistle (#d8bfd8)
  • tomato (#ff6347)
  • turquoise (#40e0d0)
  • violet (#ee82ee)
  • wheat (#f5deb3)
  • white (#ffffff)
  • whitesmoke (#f5f5f5)
  • yellow (#ffff00)
  • yellowgreen (#9acd32)

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file + \ No newline at end of file diff --git a/docs/communication-ios.html b/docs/communication-ios.html index fc8f92f1c79..36deb42aa62 100644 --- a/docs/communication-ios.html +++ b/docs/communication-ios.html @@ -1,4 +1,4 @@ -Communication between native and React Native

Communication between native and React Native #

In Integrating with Existing Apps guide and Native UI Components guide we learn how to embed React Native in a native component and vice versa. When we mix native and React Native components, we'll eventually find a need to communicate between these two worlds. Some ways to achieve that have been already mentioned in other guides. This article summarizes available techniques.

Introduction #

React Native is inspired by React, so the basic idea of the information flow is similar. The flow in React is one-directional. We maintain a hierarchy of components, in which each component depends only on its parent and its own internal state. We do this with properties: data is passed from a parent to its children in a top-down manner. If an ancestor component relies on the state of its descendant, one should pass down a callback to be used by the descendant to update the ancestor.

The same concept applies to React Native. As long as we are building our application purely within the framework, we can drive our app with properties and callbacks. But, when we mix React Native and native components, we need some special, cross-language mechanisms that would allow us to pass information between them.

Properties #

Properties are the simplest way of cross-component communication. So we need a way to pass properties both from native to React Native, and from React Native to native.

Passing properties from native to React Native #

In order to embed a React Native view in a native component, we use RCTRootView. RCTRootView is a UIView that holds a React Native app. It also provides an interface between native side and the hosted app.

RCTRootView has an initializer that allows you to pass arbitrary properties down to the React Native app. The initialProperties parameter has to be an instance of NSDictionary. The dictionary is internally converted into a JSON object that the top-level JS component can reference.

NSArray *imageList = @[@"http://foo.com/bar1.png", +Communication between native and React Native

Communication between native and React Native #

In Integrating with Existing Apps guide and Native UI Components guide we learn how to embed React Native in a native component and vice versa. When we mix native and React Native components, we'll eventually find a need to communicate between these two worlds. Some ways to achieve that have been already mentioned in other guides. This article summarizes available techniques.

Introduction #

React Native is inspired by React, so the basic idea of the information flow is similar. The flow in React is one-directional. We maintain a hierarchy of components, in which each component depends only on its parent and its own internal state. We do this with properties: data is passed from a parent to its children in a top-down manner. If an ancestor component relies on the state of its descendant, one should pass down a callback to be used by the descendant to update the ancestor.

The same concept applies to React Native. As long as we are building our application purely within the framework, we can drive our app with properties and callbacks. But, when we mix React Native and native components, we need some special, cross-language mechanisms that would allow us to pass information between them.

Properties #

Properties are the simplest way of cross-component communication. So we need a way to pass properties both from native to React Native, and from React Native to native.

Passing properties from native to React Native #

In order to embed a React Native view in a native component, we use RCTRootView. RCTRootView is a UIView that holds a React Native app. It also provides an interface between native side and the hosted app.

RCTRootView has an initializer that allows you to pass arbitrary properties down to the React Native app. The initialProperties parameter has to be an instance of NSDictionary. The dictionary is internally converted into a JSON object that the top-level JS component can reference.

NSArray *imageList = @[@"http://foo.com/bar1.png", @"http://foo.com/bar2.png"]; NSDictionary *props = @{@"images" : imageList}; @@ -74,7 +74,7 @@ Making a dimension flexible in both JS and native leads to undefined behavior. F newFrame.size = rootView.intrinsicContentSize; rootView.frame = newFrame; -}

In the example we have a FlexibleSizeExampleView view that holds a root view. We create the root view, initialize it and set the delegate. The delegate will handle size updates. Then, we set the root view's size flexibility to RCTRootViewSizeFlexibilityHeight, which means that rootViewDidChangeIntrinsicSize: method will be called every time the React Native content changes its height. Finally, we set the root view's width and position. Note that we set there height as well, but it has no effect as we made the height RN-dependent.

You can checkout full source code of the example here.

It's fine to change root view's size flexibility mode dynamically. Changing flexibility mode of a root view will schedule a layout recalculation and the delegate rootViewDidChangeIntrinsicSize: method will be called once the content size is known.

Note: React Native layout calculation is performed on a special thread, while native UI view updates are done on the main thread. This may cause temporary UI inconsistencies between native and React Native. This is a known problem and our team is working on synchronizing UI updates coming from different sources.

Note: React Native does not perform any layout calculations until the root view becomes a subview of some other views. If you want to hide React Native view until its dimensions are known, add the root view as a subview and make it initially hidden (use UIView's hidden property). Then change its visibility in the delegate method.

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file + \ No newline at end of file diff --git a/docs/datepickerandroid.html b/docs/datepickerandroid.html index 8761f21bbdb..a31f7192423 100644 --- a/docs/datepickerandroid.html +++ b/docs/datepickerandroid.html @@ -1,4 +1,4 @@ -DatePickerAndroid

DatePickerAndroid #

Opens the standard Android date picker dialog.

Example #

try { +DatePickerAndroid

DatePickerAndroid #

Opens the standard Android date picker dialog.

Example #

try { const {action, year, month, day} = await DatePickerAndroid.open({ // Use `new Date()` for current date. // May 25 2020. Month 0 is January. @@ -9,135 +9,11 @@ } } catch ({code, message}) { console.warn('Cannot open date picker', message); -}

Methods #

static open(options) #

Opens the standard Android date picker dialog.

The available keys for the options object are:

  • date (Date object or timestamp in milliseconds) - date to show by default
  • minDate (Date or timestamp in milliseconds) - minimum date that can be selected
  • maxDate (Date object or timestamp in milliseconds) - minimum date that can be selected
  • mode (enum('calendar', 'spinner', 'default')) - To set the date-picker mode to calendar/spinner/default
    • 'calendar': Show a date picker in calendar mode.
    • 'spinner': Show a date picker in spinner mode.
    • 'default': Show a default native date picker(spinner/calendar) based on android versions.

Returns a Promise which will be invoked an object containing action, year, month (0-11), +}

Methods #

static open(options) #

Opens the standard Android date picker dialog.

The available keys for the options object are:

  • date (Date object or timestamp in milliseconds) - date to show by default
  • minDate (Date or timestamp in milliseconds) - minimum date that can be selected
  • maxDate (Date object or timestamp in milliseconds) - maximum date that can be selected
  • mode (enum('calendar', 'spinner', 'default')) - To set the date-picker mode to calendar/spinner/default
    • 'calendar': Show a date picker in calendar mode.
    • 'spinner': Show a date picker in spinner mode.
    • 'default': Show a default native date picker(spinner/calendar) based on android versions.

Returns a Promise which will be invoked an object containing action, year, month (0-11), day if the user picked a date. If the user dismissed the dialog, the Promise will still be resolved with action being DatePickerAndroid.dismissedAction and all the other keys being undefined. Always check whether the action before reading the values.

Note the native date picker dialog has some UI glitches on Android 4 and lower -when using the minDate and maxDate options.

static dateSetAction() #

A date has been selected.

static dismissedAction() #

The dialog has been dismissed.

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - DatePickerAndroid, - StyleSheet, - Text, - TouchableWithoutFeedback, -} = ReactNative; - -var UIExplorerBlock = require('./UIExplorerBlock'); -var UIExplorerPage = require('./UIExplorerPage'); - -class DatePickerAndroidExample extends React.Component { - static title = 'DatePickerAndroid'; - static description = 'Standard Android date picker dialog'; - - state = { - presetDate: new Date(2020, 4, 5), - simpleDate: new Date(2020, 4, 5), - spinnerDate: new Date(2020, 4, 5), - calendarDate: new Date(2020, 4, 5), - defaultDate: new Date(2020, 4, 5), - allDate: new Date(2020, 4, 5), - simpleText: 'pick a date', - spinnerText: 'pick a date', - calendarText: 'pick a date', - defaultText: 'pick a date', - minText: 'pick a date, no earlier than today', - maxText: 'pick a date, no later than today', - presetText: 'pick a date, preset to 2020/5/5', - allText: 'pick a date between 2020/5/1 and 2020/5/10', - }; - - showPicker = async (stateKey, options) => { - try { - var newState = {}; - const {action, year, month, day} = await DatePickerAndroid.open(options); - if (action === DatePickerAndroid.dismissedAction) { - newState[stateKey + 'Text'] = 'dismissed'; - } else { - var date = new Date(year, month, day); - newState[stateKey + 'Text'] = date.toLocaleDateString(); - newState[stateKey + 'Date'] = date; - } - this.setState(newState); - } catch ({code, message}) { - console.warn(`Error in example '${stateKey}': `, message); - } - }; - - render() { - return ( - <UIExplorerPage title="DatePickerAndroid"> - <UIExplorerBlock title="Simple date picker"> - <TouchableWithoutFeedback - onPress={this.showPicker.bind(this, 'simple', {date: this.state.simpleDate})}> - <Text style={styles.text}>{this.state.simpleText}</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Simple spinner date picker"> - <TouchableWithoutFeedback - onPress={this.showPicker.bind(this, 'spinner', {date: this.state.spinnerDate, mode: 'spinner'})}> - <Text style={styles.text}>{this.state.spinnerText}</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Simple calendar date picker"> - <TouchableWithoutFeedback - onPress={this.showPicker.bind(this, 'calendar', {date: this.state.calendarDate, mode: 'calendar'})}> - <Text style={styles.text}>{this.state.calendarText}</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Simple default date picker"> - <TouchableWithoutFeedback - onPress={this.showPicker.bind(this, 'default', {date: this.state.defaultDate, mode: 'default'})}> - <Text style={styles.text}>{this.state.defaultText}</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Date picker with pre-set date"> - <TouchableWithoutFeedback - onPress={this.showPicker.bind(this, 'preset', {date: this.state.presetDate})}> - <Text style={styles.text}>{this.state.presetText}</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Date picker with minDate"> - <TouchableWithoutFeedback - onPress={this.showPicker.bind(this, 'min', { - date: this.state.minDate, - minDate: new Date(), - })}> - <Text style={styles.text}>{this.state.minText}</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Date picker with maxDate"> - <TouchableWithoutFeedback - onPress={this.showPicker.bind(this, 'max', { - date: this.state.maxDate, - maxDate: new Date(), - })}> - <Text style={styles.text}>{this.state.maxText}</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Date picker with all options"> - <TouchableWithoutFeedback - onPress={this.showPicker.bind(this, 'all', { - date: this.state.allDate, - minDate: new Date(2020, 4, 1), - maxDate: new Date(2020, 4, 10), - })}> - <Text style={styles.text}>{this.state.allText}</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - </UIExplorerPage> - ); - } -} - -var styles = StyleSheet.create({ - text: { - color: 'black', - }, -}); - -module.exports = DatePickerAndroidExample;
\ No newline at end of file + \ No newline at end of file diff --git a/docs/datepickerios.html b/docs/datepickerios.html index 545fb89a99a..2bcc4205417 100644 --- a/docs/datepickerios.html +++ b/docs/datepickerios.html @@ -1,161 +1,12 @@ -DatePickerIOS

DatePickerIOS #

Use DatePickerIOS to render a date/time picker (selector) on iOS. This is +DatePickerIOS

DatePickerIOS #

Use DatePickerIOS to render a date/time picker (selector) on iOS. This is a controlled component, so you must hook in to the onDateChange callback and update the date prop in order for the component to update, otherwise the user's change will be reverted immediately to reflect props.date as the -source of truth.

Props #

date: Date #

The currently selected date.

maximumDate?: Date #

Maximum date.

Restricts the range of possible date/time values.

minimumDate?: Date #

Minimum date.

Restricts the range of possible date/time values.

minuteInterval?: enum(1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30) #

The interval at which minutes can be selected.

mode?: enum('date', 'time', 'datetime') #

The date picker mode.

onDateChange: function #

Date change handler.

This is called when the user changes the date or time in the UI. +source of truth.

Props #

date?: PropTypes.instanceOf(Date).isRequired #

The currently selected date.

maximumDate?: PropTypes.instanceOf(Date) #

Maximum date.

Restricts the range of possible date/time values.

minimumDate?: PropTypes.instanceOf(Date) #

Minimum date.

Restricts the range of possible date/time values.

minuteInterval?: PropTypes.oneOf([1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30]) #

The interval at which minutes can be selected.

mode?: PropTypes.oneOf(['date', 'time', 'datetime']) #

The date picker mode.

onDateChange?: PropTypes.func.isRequired #

Date change handler.

This is called when the user changes the date or time in the UI. The first and only argument is a Date object representing the new -date and time.

timeZoneOffsetInMinutes?: number #

Timezone offset in minutes.

By default, the date picker will use the device's timezone. With this +date and time.

timeZoneOffsetInMinutes?: PropTypes.number #

Timezone offset in minutes.

By default, the date picker will use the device's timezone. With this parameter, it is possible to force a certain timezone offset. For -instance, to show times in Pacific Standard Time, pass -7 * 60.

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - DatePickerIOS, - StyleSheet, - Text, - TextInput, - View, -} = ReactNative; - -class DatePickerExample extends React.Component { - static defaultProps = { - date: new Date(), - timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset() / 60, - }; - - state = { - date: this.props.date, - timeZoneOffsetInHours: this.props.timeZoneOffsetInHours, - }; - - onDateChange = (date) => { - this.setState({date: date}); - }; - - onTimezoneChange = (event) => { - var offset = parseInt(event.nativeEvent.text, 10); - if (isNaN(offset)) { - return; - } - this.setState({timeZoneOffsetInHours: offset}); - }; - - render() { - // Ideally, the timezone input would be a picker rather than a - // text input, but we don't have any pickers yet :( - return ( - <View> - <WithLabel label="Value:"> - <Text>{ - this.state.date.toLocaleDateString() + - ' ' + - this.state.date.toLocaleTimeString() - }</Text> - </WithLabel> - <WithLabel label="Timezone:"> - <TextInput - onChange={this.onTimezoneChange} - style={styles.textinput} - value={this.state.timeZoneOffsetInHours.toString()} - /> - <Text> hours from UTC</Text> - </WithLabel> - <Heading label="Date + time picker" /> - <DatePickerIOS - date={this.state.date} - mode="datetime" - timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60} - onDateChange={this.onDateChange} - /> - <Heading label="Date picker" /> - <DatePickerIOS - date={this.state.date} - mode="date" - timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60} - onDateChange={this.onDateChange} - /> - <Heading label="Time picker, 10-minute interval" /> - <DatePickerIOS - date={this.state.date} - mode="time" - timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60} - onDateChange={this.onDateChange} - minuteInterval={10} - /> - </View> - ); - } -} - -class WithLabel extends React.Component { - render() { - return ( - <View style={styles.labelContainer}> - <View style={styles.labelView}> - <Text style={styles.label}> - {this.props.label} - </Text> - </View> - {this.props.children} - </View> - ); - } -} - -class Heading extends React.Component { - render() { - return ( - <View style={styles.headingContainer}> - <Text style={styles.heading}> - {this.props.label} - </Text> - </View> - ); - } -} - -exports.displayName = (undefined: ?string); -exports.title = '<DatePickerIOS>'; -exports.description = 'Select dates and times using the native UIDatePicker.'; -exports.examples = [ -{ - title: '<DatePickerIOS>', - render: function(): React.Element<any> { - return <DatePickerExample />; - }, -}]; - -var styles = StyleSheet.create({ - textinput: { - height: 26, - width: 50, - borderWidth: 0.5, - borderColor: '#0f0f0f', - padding: 4, - fontSize: 13, - }, - labelContainer: { - flexDirection: 'row', - alignItems: 'center', - marginVertical: 2, - }, - labelView: { - marginRight: 10, - paddingVertical: 2, - }, - label: { - fontWeight: '500', - }, - headingContainer: { - padding: 4, - backgroundColor: '#f6f7f8', - }, - heading: { - fontWeight: '500', - fontSize: 14, - }, -});
\ No newline at end of file + \ No newline at end of file diff --git a/docs/debugging.html b/docs/debugging.html index 2abcb7d29c7..868050cd460 100644 --- a/docs/debugging.html +++ b/docs/debugging.html @@ -1,5 +1,18 @@ -Debugging

Debugging #

Enabling Keyboard Shortcuts #

React Native supports a few keyboard shortcuts in the iOS Simulator. They are described below. To enable them, open the Hardware menu, select Keyboard, and make sure that "Connect Hardware Keyboard" is checked.

Accessing the In-App Developer Menu #

You can access the developer menu by shaking your device or by selecting "Shake Gesture" inside the Hardware menu in the iOS Simulator. You can also use the Command + D keyboard shortcut when your app is running in the iPhone Simulator, or Command + M when running in an Android emulator.

The Developer Menu is disabled in release (production) builds.

Reloading JavaScript #

Instead of recompiling your app every time you make a change, you can reload your app's JavaScript code instantly. To do so, select "Reload" from the Developer Menu. You can also press Command + R in the iOS Simulator, or press R twice on Android emulators.

Automatic reloading #

You can speed up your development times by having your app reload automatically any time your code changes. Automatic reloading can be enabled by selecting "Enable Live Reload" from the Developer Menu.

You may even go a step further and keep your app running as new versions of your files are injected into the JavaScript bundle automatically by enabling Hot Reloading from the Developer Menu. This will allow you to persist the app's state through reloads.

There are some instances where hot reloading cannot be implemented perfectly. If you run into any issues, use a full reload to reset your app.

You will need to rebuild your app for changes to take effect in certain situations:

  • You have added new resources to your native app's bundle, such as an image in Images.xcassets on iOS or the res/drawable folder on Android.
  • You have modified native code (Objective-C/Swift on iOS or Java/C++ on Android).

In-app Errors and Warnings #

Errors and warnings are displayed inside your app in development builds.

Errors #

In-app errors are displayed in a full screen alert with a red background inside your app. This screen is known as a RedBox. You can use console.error() to manually trigger one.

Warnings #

Warnings will be displayed on screen with a yellow background. These alerts are known as YellowBoxes. Click on the alerts to show more information or to dismiss them.

As with a RedBox, you can use console.warn() to trigger a YellowBox.

YellowBoxes can be disabled during development by using console.disableYellowBox = true;. Specific warnings can be ignored programmatically by setting an array of prefixes that should be ignored: console.ignoredYellowBox = ['Warning: ...'];.

In CI/Xcode, YellowBoxes can also be disabled by setting the IS_TESTING environment variable.

RedBoxes and YellowBoxes are automatically disabled in release (production) builds.

Accessing console logs #

You can display the console logs for an iOS or Android app by using the following commands in a terminal while the app is running:

$ react-native log-ios -$ react-native log-android

You may also access these through Debug → Open System Log... in the iOS Simulator or by running adb logcat *:S ReactNative:V ReactNativeJS:V in a terminal while an Android app is running on a device or emulator.

Chrome Developer Tools #

To debug the JavaScript code in Chrome, select "Debug JS Remotely" from the Developer Menu. This will open a new tab at http://localhost:8081/debugger-ui.

Select Tools → Developer Tools from the Chrome Menu to open the Developer Tools. You may also access the DevTools using keyboard shortcuts (Command + Option + I on Mac, Ctrl + Shift + I on Windows). You may also want to enable Pause On Caught Exceptions for a better debugging experience.

It is currently not possible to use the "React" tab in the Chrome Developer Tools to inspect app widgets. You can use Nuclide's "React Native Inspector" as a workaround.

Debugging on a device with Chrome Developer Tools #

On iOS devices, open the file RCTWebSocketExecutor.m and change "localhost" to the IP address of your computer, then select "Debug JS Remotely" from the Developer Menu.

On Android 5.0+ devices connected via USB, you can use the adb command line tool to setup port forwarding from the device to your computer:

adb reverse tcp:8081 tcp:8081

Alternatively, select "Dev Settings" from the Developer Menu, then update the "Debug server host for device" setting to match the IP address of your computer.

If you run into any issues, it may be possible that one of your Chrome extensions is interacting in unexpected ways with the debugger. Try disabling all of your extensions and re-enabling them one-by-one until you find the problematic extension.

Debugging using a custom JavaScript debugger #

To use a custom JavaScript debugger in place of Chrome Developer Tools, set the REACT_DEBUGGER environment variable to a command that will start your custom debugger. You can then select "Debug JS Remotely" from the Developer Menu to start debugging.

The debugger will receive a list of all project roots, separated by a space. For example, if you set REACT_DEBUGGER="node /path/to/launchDebugger.js --port 2345 --type ReactNative", then the command node /path/to/launchDebugger.js --port 2345 --type ReactNative /path/to/reactNative/app will be used to start your debugger.

Custom debugger commands executed this way should be short-lived processes, and they shouldn't produce more than 200 kilobytes of output.

Debugging with Stetho on Android #

  1. In android/app/build.gradle, add these lines in the dependencies section:

    compile 'com.facebook.stetho:stetho:1.3.1' +Debugging

    Debugging #

    Enabling Keyboard Shortcuts #

    React Native supports a few keyboard shortcuts in the iOS Simulator. They are described below. To enable them, open the Hardware menu, select Keyboard, and make sure that "Connect Hardware Keyboard" is checked.

    Accessing the In-App Developer Menu #

    You can access the developer menu by shaking your device or by selecting "Shake Gesture" inside the Hardware menu in the iOS Simulator. You can also use the ⌘D keyboard shortcut when your app is running in the iOS Simulator, or ⌘M when running in an Android emulator.

    The Developer Menu is disabled in release (production) builds.

    Reloading JavaScript #

    Instead of recompiling your app every time you make a change, you can reload your app's JavaScript code instantly. To do so, select "Reload" from the Developer Menu. You can also press ⌘R in the iOS Simulator, or tap R twice on Android emulators.

    Automatic reloading #

    You can speed up your development times by having your app reload automatically any time your code changes. Automatic reloading can be enabled by selecting "Enable Live Reload" from the Developer Menu.

    You may even go a step further and keep your app running as new versions of your files are injected into the JavaScript bundle automatically by enabling Hot Reloading from the Developer Menu. This will allow you to persist the app's state through reloads.

    There are some instances where hot reloading cannot be implemented perfectly. If you run into any issues, use a full reload to reset your app.

    You will need to rebuild your app for changes to take effect in certain situations:

    • You have added new resources to your native app's bundle, such as an image in Images.xcassets on iOS or the res/drawable folder on Android.
    • You have modified native code (Objective-C/Swift on iOS or Java/C++ on Android).

    In-app Errors and Warnings #

    Errors and warnings are displayed inside your app in development builds.

    Errors #

    In-app errors are displayed in a full screen alert with a red background inside your app. This screen is known as a RedBox. You can use console.error() to manually trigger one.

    Warnings #

    Warnings will be displayed on screen with a yellow background. These alerts are known as YellowBoxes. Click on the alerts to show more information or to dismiss them.

    As with a RedBox, you can use console.warn() to trigger a YellowBox.

    YellowBoxes can be disabled during development by using console.disableYellowBox = true;. Specific warnings can be ignored programmatically by setting an array of prefixes that should be ignored: console.ignoredYellowBox = ['Warning: ...'];.

    In CI/Xcode, YellowBoxes can also be disabled by setting the IS_TESTING environment variable.

    RedBoxes and YellowBoxes are automatically disabled in release (production) builds.

    Chrome Developer Tools #

    To debug the JavaScript code in Chrome, select "Debug JS Remotely" from the Developer Menu. This will open a new tab at http://localhost:8081/debugger-ui.

    Select Tools → Developer Tools from the Chrome Menu to open the Developer Tools. You may also access the DevTools using keyboard shortcuts (⌘⌥I on macOS, Ctrl Shift I on Windows). You may also want to enable Pause On Caught Exceptions for a better debugging experience.

    Note: the React Developer Tools Chrome extension does not work with React Native, but you can use its standalone version instead. Read this section to learn how.

    Debugging using a custom JavaScript debugger #

    To use a custom JavaScript debugger in place of Chrome Developer Tools, set the REACT_DEBUGGER environment variable to a command that will start your custom debugger. You can then select "Debug JS Remotely" from the Developer Menu to start debugging.

    The debugger will receive a list of all project roots, separated by a space. For example, if you set REACT_DEBUGGER="node /path/to/launchDebugger.js --port 2345 --type ReactNative", then the command node /path/to/launchDebugger.js --port 2345 --type ReactNative /path/to/reactNative/app will be used to start your debugger.

    Custom debugger commands executed this way should be short-lived processes, and they shouldn't produce more than 200 kilobytes of output.

    React Developer Tools #

    You can use the standalone version of React Developer Tools to debug the React component hierarchy. To use it, install the react-devtools package globally:

    npm install -g react-devtools

    Now run react-devtools from the terminal to launch the standalone DevTools app:

    react-devtools

    React DevTools

    It should connect to your simulator within a few seconds.

    Note: if you prefer to avoid global installations, you can add react-devtools as a project dependency. Add the react-devtools package to your project using npm install --save-dev react-devtools, then add "react-devtools": "react-devtools" to the scripts section in your package.json, and then run npm run react-devtools from your project folder to open the DevTools.

    Integration with React Native Inspector #

    Open the in-app developer menu and choose "Show Inspector". It will bring up an overlay that lets you tap on any UI element and see information about it:

    React Native Inspector

    However, when react-devtools is running, Inspector will enter a special collapsed mode, and instead use the DevTools as primary UI. In this mode, clicking on something in the simulator will bring up the relevant components in the DevTools:

    React DevTools Inspector Integration

    You can choose "Hide Inspector" in the same menu to exit this mode.

    Inspecting Component Instances #

    When debugging JavaScript in Chrome, you can inspect the props and state of the React components in the browser console.

    First, follow the instructions for debugging in Chrome to open the Chrome console.

    Make sure that the dropdown in the top left corner of the Chrome console says debuggerWorker.js. This step is essential.

    Then select a React component in React DevTools. There is a search box at the top that helps you find one by name. As soon as you select it, it will be available as $r in the Chrome console, letting you inspect its props, state, and instance properties.

    React DevTools Chrome Console Integration

    Performance Monitor #

    You can enable a performance overlay to help you debug performance problems by selecting "Perf Monitor" in the Developer Menu.


    + +

    Debugging in Ejected Apps #

    + +

    Accessing console logs #

    You can display the console logs for an iOS or Android app by using the following commands in a terminal while the app is running:

    $ react-native log-ios +$ react-native log-android

    You may also access these through Debug → Open System Log... in the iOS Simulator or by running adb logcat *:S ReactNative:V ReactNativeJS:V in a terminal while an Android app is running on a device or emulator.

    If you're using Create React Native App, console logs already appear in the same terminal output as the packager.

    Debugging on a device with Chrome Developer Tools #

    If you're using Create React Native App, this is configured for you already.

    On iOS devices, open the file RCTWebSocketExecutor.m and change "localhost" to the IP address of your computer, then select "Debug JS Remotely" from the Developer Menu.

    On Android 5.0+ devices connected via USB, you can use the adb command line tool to setup port forwarding from the device to your computer:

    adb reverse tcp:8081 tcp:8081

    Alternatively, select "Dev Settings" from the Developer Menu, then update the "Debug server host for device" setting to match the IP address of your computer.

    If you run into any issues, it may be possible that one of your Chrome extensions is interacting in unexpected ways with the debugger. Try disabling all of your extensions and re-enabling them one-by-one until you find the problematic extension.

    Debugging with Stetho on Android #

    1. In android/app/build.gradle, add these lines in the dependencies section:

      compile 'com.facebook.stetho:stetho:1.3.1' compile 'com.facebook.stetho:stetho-okhttp3:1.3.1'
    2. In android/app/src/main/java/com/{yourAppName}/MainApplication.java, add the following imports:

      import com.facebook.react.modules.network.ReactCookieJarContainer; import com.facebook.stetho.Stetho; import okhttp3.OkHttpClient; @@ -16,7 +29,7 @@ import java.util.addNetworkInterceptor(new StethoInterceptor()) .build(); OkHttpClientProvider.replaceOkHttpClient(client); -}
    3. Run react-native run-android

    4. In a new chrome tab, open : chrome://inspect, click on 'Inspect device' (the one followed by "Powered by Stetho")

    Debugging native code #

    When working with native code (e.g. when writing native modules) you can launch the app from Android Studio or Xcode and take advantage of the debugging features (setup breakpoints, etc.) as you would in case of building a standard native app.

    Performance Monitor #

    You can enable a performance overlay to help you debug performance problems by selecting "Perf Monitor" in the Developer Menu.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/dimensions.html b/docs/dimensions.html index 60553b0c5e6..0e058f7db9c 100644 --- a/docs/dimensions.html +++ b/docs/dimensions.html @@ -1,4 +1,4 @@ -Dimensions

    Dimensions #

    Methods #

    static set(dims) #

    This should only be called from native code by sending the +Dimensions

    Dimensions #

    Methods #

    static set(dims) #

    This should only be called from native code by sending the didUpdateDimensions event.

    @param {object} dims Simple string-keyed object of dimensions to set

    static get(dim) #

    Initial dimensions are set before runApplication is called so they should be available before any other require's are run, but may be updated later.

    Note: Although dimensions are available immediately, they may change (e.g due to device rotation) so any rendering logic or styles that depend on @@ -24,6 +24,6 @@ are the same as the return values of Dimensions.get('window') \ No newline at end of file + \ No newline at end of file diff --git a/docs/direct-manipulation.html b/docs/direct-manipulation.html index ca9b244705c..14864e8155f 100644 --- a/docs/direct-manipulation.html +++ b/docs/direct-manipulation.html @@ -1,4 +1,4 @@ -Direct Manipulation

    Direct Manipulation #

    It is sometimes necessary to make changes directly to a component +Direct Manipulation

    Direct Manipulation #

    It is sometimes necessary to make changes directly to a component without using state/props to trigger a re-render of the entire subtree. When using React in the browser for example, you sometimes need to directly modify a DOM node, and the same is true for views in mobile @@ -50,7 +50,10 @@ you will notice that it is a wrapper around RCTUIManager.updateView this is the exact same function call that results from re-rendering - see receiveComponent in ReactNativeBaseComponent.js.

    Composite components and setNativeProps #

    Composite components are not backed by a native view, so you cannot call -setNativeProps on them. Consider this example:

    class MyButton extends React.Component { +setNativeProps on them. Consider this example:

    If you run this you will immediately see this error: Touchable child must either be native or forward setNativeProps to a native component. This occurs because MyButton isn't directly backed by a native view whose opacity should be set. You can think about it like this: if you @@ -78,8 +81,11 @@ pass the style prop down to a child, unless you are wrapping a native component. Similarly, we are going to forward setNativeProps to a native-backed child component.

    Forward setNativeProps to a child #

    All we need to do is provide a setNativeProps method on our component that calls setNativeProps on the appropriate child with the given -arguments.

    class MyButton extends React.Component { - setNativeProps(nativeProps) { +arguments.

    You can now use MyButton inside of TouchableOpacity! A sidenote for clarity: we used the ref callback syntax here, rather than the traditional string-based ref.

    You may have noticed that we passed all of the props down to the child view using {...this.props}. The reason for this is that TouchableOpacity is actually a composite component, and so in addition @@ -105,34 +121,32 @@ characters when the bufferDelay is low and the user types very quickly. Some developers prefer to skip this prop entirely and instead use setNativeProps to directly manipulate the TextInput value when necessary. For example, the following code demonstrates clearing the -input when you tap a button:

    class App extends React.Component { - constructor(props) { - super(props); - this.clearText = this.clearText.bind(this); - } +input when you tap a button:

    Avoiding conflicts with the render function #

    If you update a property that is also managed by the render function, you might end up with some unpredictable and confusing bugs because anytime the component re-renders and that property changes, whatever value was previously set from setNativeProps will be completely -ignored and overridden. See this example -for a demonstration of what can happen if these two collide - notice -the jerky animation each 250ms when setState triggers a re-render.

    setNativeProps & shouldComponentUpdate #

    By intelligently applying +ignored and overridden.

    setNativeProps & shouldComponentUpdate #

    By intelligently applying shouldComponentUpdate you can avoid the unnecessary overhead involved in reconciling unchanged component subtrees, to the point where it may be performant enough to @@ -152,6 +166,6 @@ use setState instead of setNativeProps.

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/drawerlayoutandroid.html b/docs/drawerlayoutandroid.html index d2fdc6026c6..2a37f590e18 100644 --- a/docs/drawerlayoutandroid.html +++ b/docs/drawerlayoutandroid.html @@ -1,4 +1,4 @@ -DrawerLayoutAndroid

    DrawerLayoutAndroid #

    React component that wraps the platform DrawerLayout (Android only). The +DrawerLayoutAndroid

    DrawerLayoutAndroid #

    React component that wraps the platform DrawerLayout (Android only). The Drawer (typically used for navigation) is rendered with renderNavigationView and direct children are the main view (where your content goes). The navigation view is initially not visible on the screen, but can be pulled in from the @@ -24,18 +24,28 @@ be set by the drawerWidth prop.

    Example:

    return ( <DrawerLayoutAndroid drawerBackgroundColor="rgba(0,0,0,0.5)"> </DrawerLayoutAndroid> -);

    drawerLockMode?: enum('unlocked', 'locked-closed', 'locked-open') #

    Specifies the lock mode of the drawer. The drawer can be locked in 3 states: +);

    drawerLockMode?: PropTypes.oneOf([ + 'unlocked', + 'locked-closed', + 'locked-open' +]) #

    Specifies the lock mode of the drawer. The drawer can be locked in 3 states: - unlocked (default), meaning that the drawer will respond (open/close) to touch gestures. - locked-closed, meaning that the drawer will stay closed and not respond to gestures. - locked-open, meaning that the drawer will stay opened and not respond to gestures. -The drawer may still be opened and closed programmatically (openDrawer/closeDrawer).

    drawerPosition?: enum(DrawerConsts.DrawerPosition.Left, DrawerConsts.DrawerPosition.Right) #

    Specifies the side of the screen from which the drawer will slide in.

    drawerWidth?: number #

    Specifies the width of the drawer, more precisely the width of the view that be pulled in -from the edge of the window.

    keyboardDismissMode?: enum('none', 'on-drag') #

    Determines whether the keyboard gets dismissed in response to a drag. +The drawer may still be opened and closed programmatically (openDrawer/closeDrawer).

    drawerPosition?: PropTypes.oneOf([ + DrawerConsts.DrawerPosition.Left, + DrawerConsts.DrawerPosition.Right +]) #

    Specifies the side of the screen from which the drawer will slide in.

    drawerWidth?: PropTypes.number #

    Specifies the width of the drawer, more precisely the width of the view that be pulled in +from the edge of the window.

    keyboardDismissMode?: PropTypes.oneOf([ + 'none', // default + 'on-drag', +]) #

    Determines whether the keyboard gets dismissed in response to a drag. - 'none' (the default), drags do not dismiss the keyboard. - - 'on-drag', the keyboard is dismissed when a drag begins.

    onDrawerClose?: function #

    Function called whenever the navigation view has been closed.

    onDrawerOpen?: function #

    Function called whenever the navigation view has been opened.

    onDrawerSlide?: function #

    Function called whenever there is an interaction with the navigation view.

    onDrawerStateChanged?: function #

    Function called when the drawer state has changed. The drawer can be in 3 states: + - 'on-drag', the keyboard is dismissed when a drag begins.

    onDrawerClose?: PropTypes.func #

    Function called whenever the navigation view has been closed.

    onDrawerOpen?: PropTypes.func #

    Function called whenever the navigation view has been opened.

    onDrawerSlide?: PropTypes.func #

    Function called whenever there is an interaction with the navigation view.

    onDrawerStateChanged?: PropTypes.func #

    Function called when the drawer state has changed. The drawer can be in 3 states: - idle, meaning there is no interaction with the navigation view happening at the time - dragging, meaning there is currently an interaction with the navigation view - settling, meaning that there was an interaction with the navigation view, and the -navigation view is now finishing its closing or opening animation

    renderNavigationView: function #

    The navigation view that will be rendered to the side of the screen and can be pulled in.

    statusBarBackgroundColor?: color #

    Make the drawer take the entire screen and draw the background of the +navigation view is now finishing its closing or opening animation

    renderNavigationView?: PropTypes.func.isRequired #

    The navigation view that will be rendered to the side of the screen and can be pulled in.

    statusBarBackgroundColor?: color #

    Make the drawer take the entire screen and draw the background of the status bar to allow it to open over the status bar. It will only have an effect on API 21+.

    Methods #

    openDrawer() #

    Opens the drawer.

    closeDrawer() #

    Closes the drawer.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/easing.html b/docs/easing.html index faaa550cf0d..2b331ab2e1b 100644 --- a/docs/easing.html +++ b/docs/easing.html @@ -1,4 +1,4 @@ -Easing

    Easing #

    The Easing module implements common easing functions. This module is used +Easing

    Easing #

    The Easing module implements common easing functions. This module is used by Animate.timing() to convey physically believable motion in animations.

    You can find a visualization of some common easing functions at http://easings.net/

    Predefined animations #

    The Easing module provides several predefined animations through the @@ -33,6 +33,6 @@ duration.

    You can < apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/flatlist.html b/docs/flatlist.html index fbc8687a635..b25309b2019 100644 --- a/docs/flatlist.html +++ b/docs/flatlist.html @@ -1,4 +1,4 @@ -FlatList

    FlatList #

    A performant interface for rendering simple, flat lists, supporting the most handy features:

    • Fully cross-platform.
    • Optional horizontal mode.
    • Configurable viewability callbacks.
    • Header support.
    • Footer support.
    • Separator support.
    • Pull to Refresh.
    • Scroll loading.
    • ScrollToIndex support.

    If you need section support, use <SectionList>.

    Minimal Example:

    <FlatList +FlatList

    FlatList #

    A performant interface for rendering simple, flat lists, supporting the most handy features:

    • Fully cross-platform.
    • Optional horizontal mode.
    • Configurable viewability callbacks.
    • Header support.
    • Footer support.
    • Separator support.
    • Pull to Refresh.
    • Scroll loading.
    • ScrollToIndex support.

    If you need section support, use <SectionList>.

    Minimal Example:

    <FlatList data={[{key: 'a'}, {key: 'b'}]} renderItem={({item}) => <Text>{item.key}</Text>} />

    More complex example demonstrating PureComponent usage for perf optimization and avoiding bugs.

    • By binding the onPressItem handler, the props will remain === and PureComponent will @@ -31,7 +31,7 @@ class MyList extends this.setState((state) => { // copy the map rather than modifying state. const selected = new Map(state.selected); - selected.set(id, !state.get(id)); // toggle + selected.set(id, !selected.get(id)); // toggle return {selected}; }); }; @@ -56,18 +56,25 @@ class MyList extends ); } }

    This is a convenience wrapper around <VirtualizedList>, -and thus inherits it's props that aren't explicitly listed here along with the following caveats:

    • Internal state is not preserved when content scrolls out of the render window. Make sure all +and thus inherits it's props (as well as those of ScrollView) that aren't explicitly listed +here, along with the following caveats:

      • Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.
      • This is a PureComponent which means that it will not re-render if props remain shallow- -equal. Make sure that everything your renderItem function depends on is passed as a prop that -is not === after updates, otherwise your UI may not update on changes. This includes the -data prop and parent component state.
      • In order to constrain memory and enable smooth scrolling, content is rendered asynchronously +equal. Make sure that everything your renderItem function depends on is passed as a prop +(e.g. extraData) that is not === after updates, otherwise your UI may not update on +changes. This includes the data prop and parent component state.
      • In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.
      • By default, the list looks for a key prop on each item and uses that for the React key. -Alternatively, you can provide a custom keyExtractor prop.

    Props #

    ItemSeparatorComponent?: ?ReactClass<any> #

    Rendered in between each item, but not at the top or bottom.

    ListFooterComponent?: ?ReactClass<any> #

    Rendered at the bottom of all the items.

    ListHeaderComponent?: ?ReactClass<any> #

    Rendered at the top of all the items.

    columnWrapperStyle?: StyleObj #

    Optional custom style for multi-item rows generated when numColumns > 1.

    data: ?Array<ItemT> #

    For simplicity, data is just a plain array. If you want to use something else, like an +Alternatively, you can provide a custom keyExtractor prop.

Props #

ItemSeparatorComponent?: ?ReactClass<any> #

Rendered in between each item, but not at the top or bottom. By default, highlighted and +leadingItem props are provided. renderItem provides separators.highlight/unhighlight +which will update the highlighted prop, but you can also add custom props with +separators.updateProps.

ListEmptyComponent?: ?ReactClass<any> | React.Element<any> #

Rendered when the list is empty. Can be a React Component Class, a render function, or +a rendered element.

ListFooterComponent?: ?ReactClass<any> | React.Element<any> #

Rendered at the bottom of all the items. Can be a React Component Class, a render function, or +a rendered element.

ListHeaderComponent?: ?ReactClass<any> | React.Element<any> #

Rendered at the top of all the items. Can be a React Component Class, a render function, or +a rendered element.

columnWrapperStyle?: StyleObj #

Optional custom style for multi-item rows generated when numColumns > 1.

data: ?$ReadOnlyArray<ItemT> #

For simplicity, data is just a plain array. If you want to use something else, like an immutable list, use the underlying VirtualizedList directly.

extraData?: any #

A marker property for telling the list to re-render (since it implements PureComponent). If any of your renderItem, Header, Footer, etc. functions depend on anything outside of the -data prop, stick it here and treat it immutably.

getItem?: #

getItemCount?: #

getItemLayout?: (data: ?Array<ItemT>, index: number) => +data prop, stick it here and treat it immutably.

getItemLayout?: (data: ?Array<ItemT>, index: number) => {length: number, offset: number, index: number} #

getItemLayout is an optional optimizations that let us skip measurement of dynamic content if you know the height of items a priori. getItemLayout is the most efficient, and is easy to use if you have fixed height items, for example:

getItemLayout={(data, index) => ( @@ -75,7 +82,10 @@ use if you have fixed height items, for example:

)}

Remember to include separator length (height or width) in your offset calculation if you specify ItemSeparatorComponent.

horizontal?: ?boolean #

If true, renders items next to each other horizontally instead of stacked vertically.

initialNumToRender: number #

How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order -to improve perceived performance of scroll-to-top actions.

keyExtractor: (item: ItemT, index: number) => string #

Used to extract a unique key for a given item at the specified index. Key is used for caching +to improve perceived performance of scroll-to-top actions.

initialScrollIndex?: ?number #

Instead of starting at the top with the first item, start at initialScrollIndex. This +disables the "scroll to top" optimization that keeps the first initialNumToRender items +always rendered and immediately renders the items starting at this initial index. Requires +getItemLayout to be implemented.

keyExtractor: (item: ItemT, index: number) => string #

Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks item.key, then falls back to using the index, like React does.

legacyImplementation?: ?boolean #

numColumns: number #

Multiple columns can only be rendered with horizontal={false} and will zig-zag like a flexWrap layout. Items should all be the same height - masonry layouts are not supported.

onEndReached?: ?(info: {distanceFromEnd: number}) => void #

Called once when the scroll position gets within onEndReachedThreshold of the rendered @@ -86,204 +96,40 @@ within half the visible length of the list.

refreshing prop correctly.

onViewableItemsChanged?: ?(info: { viewableItems: Array<ViewToken>, changed: Array<ViewToken>, -}) => void #

Called when the viewability of rows changes, as defined by the viewabilityConfig prop.

refreshing?: ?boolean #

Set this true while waiting for new data from a refresh.

renderItem: (info: {item: ItemT, index: number}) => ?React.Element<any> #

Takes an item from data and renders it into the list. Typical usage:

_renderItem = ({item}) => ( - <TouchableOpacity onPress={() => this._onPress(item)}> - <Text>{item.title}}</Text> - </TouchableOpacity> -); -... -<FlatList data={[{title: 'Title Text', key: 'item1'}]} renderItem={this._renderItem} />

Provides additional metadata like index if you need it.

viewabilityConfig?: ViewabilityConfig #

See ViewabilityHelper for flow type and further documentation.

Methods #

scrollToEnd(params?: object) #

Scrolls to the end of the content. May be janky without getItemLayout prop.

scrollToIndex(params: object) #

Scrolls to the item at a the specified index such that it is positioned in the viewable area +}) => void #

Called when the viewability of rows changes, as defined by the viewabilityConfig prop.

refreshing?: ?boolean #

Set this true while waiting for new data from a refresh.

removeClippedSubviews?: boolean #

Note: may have bugs (missing content) in some circumstances - use at your own risk.

This may improve scroll performance for large lists.

renderItem: (info: { + item: ItemT, + index: number, + separators: { + highlight: () => void, + unhighlight: () => void, + updateProps: (select: 'leading' | 'trailing', newProps: Object) => void, + }, +}) => ?React.Element<any> #

Takes an item from data and renders it into the list. Example usage:

<FlatList + ItemSeparatorComponent={Platform.OS !== 'android' && ({highlighted}) => ( + <View style={[style.separator, highlighted && {marginLeft: 0}]} /> + )} + data={[{title: 'Title Text', key: 'item1'}]} + renderItem={({item, separators}) => ( + <TouchableHighlight + onPress={() => this._onPress(item)} + onShowUnderlay={separators.highlight} + onHideUnderlay={separators.unhighlight}> + <View style={{backgroundColor: 'white'}}> + <Text>{item.title}}</Text> + </View> + </TouchableHighlight> + )} +/>

Provides additional metadata like index if you need it, as well as a more generic +separators.updateProps function which let's you set whatever props you want to change the +rendering of either the leading separator or trailing separator in case the more common +highlight and unhighlight (which set the highlighted: boolean prop) are insufficient for +your use-case.

viewabilityConfig?: ViewabilityConfig #

See ViewabilityHelper for flow type and further documentation.

Methods #

scrollToEnd(params?: object) #

Scrolls to the end of the content. May be janky without getItemLayout prop.

scrollToIndex(params: object) #

Scrolls to the item at a the specified index such that it is positioned in the viewable area such that viewPosition 0 places it at the top, 1 at the bottom, and 0.5 centered in the -middle.

May be janky without getItemLayout prop.

scrollToItem(params: object) #

Requires linear scan through data - use scrollToIndex instead if possible. May be janky -without getItemLayout prop.

scrollToOffset(params: object) #

Scroll to a specific content pixel offset, like a normal ScrollView.

recordInteraction() #

Tells the list an interaction has occured, which should trigger viewability calculations, e.g. +middle. viewOffset is a fixed number of pixels to offset the final target position.

Note: cannot scroll to locations outside the render window without specifying the +getItemLayout prop.

scrollToItem(params: object) #

Requires linear scan through data - use scrollToIndex instead if possible.

Note: cannot scroll to locations outside the render window without specifying the +getItemLayout prop.

scrollToOffset(params: object) #

Scroll to a specific content pixel offset, like a normal ScrollView.

recordInteraction() #

Tells the list an interaction has occured, which should trigger viewability calculations, e.g. if waitForInteractions is true and the user has not scrolled. This is typically called by -taps on items or by navigation actions.

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
'use strict'; - -const React = require('react'); -const ReactNative = require('react-native'); -const { - Animated, - FlatList, - StyleSheet, - View, -} = ReactNative; - -const UIExplorerPage = require('./UIExplorerPage'); - -const infoLog = require('infoLog'); - -const { - FooterComponent, - HeaderComponent, - ItemComponent, - PlainInput, - SeparatorComponent, - Spindicator, - genItemData, - getItemLayout, - pressItem, - renderSmallSwitchOption, -} = require('./ListExampleShared'); - -const AnimatedFlatList = Animated.createAnimatedComponent(FlatList); - -const VIEWABILITY_CONFIG = { - minimumViewTime: 3000, - viewAreaCoveragePercentThreshold: 100, - waitForInteraction: true, -}; - -class FlatListExample extends React.PureComponent { - static title = '<FlatList>'; - static description = 'Performant, scrollable list of data.'; - - state = { - data: genItemData(1000), - debug: false, - horizontal: false, - filterText: '', - fixedHeight: true, - logViewable: false, - virtualized: true, - }; - - _onChangeFilterText = (filterText) => { - this.setState({filterText}); - }; - - _onChangeScrollToIndex = (text) => { - this._listRef.getNode().scrollToIndex({viewPosition: 0.5, index: Number(text)}); - }; - - _scrollPos = new Animated.Value(0); - _scrollSinkX = Animated.event( - [{nativeEvent: { contentOffset: { x: this._scrollPos } }}], - {useNativeDriver: true}, - ); - _scrollSinkY = Animated.event( - [{nativeEvent: { contentOffset: { y: this._scrollPos } }}], - {useNativeDriver: true}, - ); - - componentDidUpdate() { - this._listRef.getNode().recordInteraction(); // e.g. flipping logViewable switch - } - - render() { - const filterRegex = new RegExp(String(this.state.filterText), 'i'); - const filter = (item) => ( - filterRegex.test(item.text) || filterRegex.test(item.title) - ); - const filteredData = this.state.data.filter(filter); - return ( - <UIExplorerPage - noSpacer={true} - noScroll={true}> - <View style={styles.searchRow}> - <View style={styles.options}> - <PlainInput - onChangeText={this._onChangeFilterText} - placeholder="Search..." - value={this.state.filterText} - /> - <PlainInput - onChangeText={this._onChangeScrollToIndex} - placeholder="scrollToIndex..." - /> - </View> - <View style={styles.options}> - {renderSmallSwitchOption(this, 'virtualized')} - {renderSmallSwitchOption(this, 'horizontal')} - {renderSmallSwitchOption(this, 'fixedHeight')} - {renderSmallSwitchOption(this, 'logViewable')} - {renderSmallSwitchOption(this, 'debug')} - <Spindicator value={this._scrollPos} /> - </View> - </View> - <SeparatorComponent /> - <AnimatedFlatList - ItemSeparatorComponent={SeparatorComponent} - ListHeaderComponent={HeaderComponent} - ListFooterComponent={FooterComponent} - data={filteredData} - debug={this.state.debug} - disableVirtualization={!this.state.virtualized} - getItemLayout={this.state.fixedHeight ? - this._getItemLayout : - undefined - } - horizontal={this.state.horizontal} - key={(this.state.horizontal ? 'h' : 'v') + - (this.state.fixedHeight ? 'f' : 'd') - } - legacyImplementation={false} - numColumns={1} - onRefresh={this._onRefresh} - onScroll={this.state.horizontal ? this._scrollSinkX : this._scrollSinkY} - onViewableItemsChanged={this._onViewableItemsChanged} - ref={this._captureRef} - refreshing={false} - renderItem={this._renderItemComponent} - viewabilityConfig={VIEWABILITY_CONFIG} - /> - </UIExplorerPage> - ); - } - _captureRef = (ref) => { this._listRef = ref; }; - _getItemLayout = (data: any, index: number) => { - return getItemLayout(data, index, this.state.horizontal); - }; - _onRefresh = () => alert('onRefresh: nothing to refresh :P'); - _renderItemComponent = ({item}) => { - return ( - <ItemComponent - item={item} - horizontal={this.state.horizontal} - fixedHeight={this.state.fixedHeight} - onPress={this._pressItem} - /> - ); - }; - // This is called when items change viewability by scrolling into or out of - // the viewable area. - _onViewableItemsChanged = (info: { - changed: Array<{ - key: string, - isViewable: boolean, - item: any, - index: ?number, - section?: any, - }> - } - ) => { - // Impressions can be logged here - if (this.state.logViewable) { - infoLog( - 'onViewableItemsChanged: ', - info.changed.map((v) => ({...v, item: '...'})), - ); - } - }; - _pressItem = (key: number) => { - this._listRef.getNode().recordInteraction(); - pressItem(this, key); - }; - _listRef: FlatList<*>; -} - - -const styles = StyleSheet.create({ - options: { - flexDirection: 'row', - flexWrap: 'wrap', - alignItems: 'center', - }, - searchRow: { - paddingHorizontal: 10, - }, -}); - -module.exports = FlatListExample;
\ No newline at end of file + \ No newline at end of file diff --git a/docs/flexbox.html b/docs/flexbox.html index 83ddd10bb3c..0672913357f 100644 --- a/docs/flexbox.html +++ b/docs/flexbox.html @@ -1,7 +1,7 @@ -Layout with Flexbox

Layout with Flexbox #

A component can specify the layout of its children using the flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes.

You will normally use a combination of flexDirection, alignItems, and justifyContent to achieve the right layout.

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter only supporting a single number.

Flex Direction #

Adding flexDirection to a component's style determines the primary axis of its layout. Should the children be organized horizontally (row) or vertically (column)? The default is column.

import React, { Component } from 'react'; +Layout with Flexbox

Layout with Flexbox #

A component can specify the layout of its children using the flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes.

You will normally use a combination of flexDirection, alignItems, and justifyContent to achieve the right layout.

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter only supporting a single number.

Flex Direction #

Adding flexDirection to a component's style determines the primary axis of its layout. Should the children be organized horizontally (row) or vertically (column)? The default is column.

import React, { Component } from 'react'; import { AppRegistry, View } from 'react-native'; -class FlexDirectionBasics extends Component { +export default class FlexDirectionBasics extends Component { render() { return ( // Try setting `flexDirection` to `column`. @@ -13,11 +13,12 @@ class FlexDirectionBasics extends ); } }; - -AppRegistry.registerComponent('AwesomeProject', () => FlexDirectionBasics);

Justify Content #

Adding justifyContent to a component's style determines the distribution of children along the primary axis. Should children be distributed at the start, the center, the end, or spaced evenly? Available options are flex-start, center, flex-end, space-around, and space-between.

import React, { Component } from 'react'; + +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => FlexDirectionBasics);

Justify Content #

Adding justifyContent to a component's style determines the distribution of children along the primary axis. Should children be distributed at the start, the center, the end, or spaced evenly? Available options are flex-start, center, flex-end, space-around, and space-between.

import React, { Component } from 'react'; import { AppRegistry, View } from 'react-native'; -class JustifyContentBasics extends Component { +export default class JustifyContentBasics extends Component { render() { return ( // Try setting `justifyContent` to `center`. @@ -34,11 +35,12 @@ class JustifyContentBasics extends ); } }; - -AppRegistry.registerComponent('AwesomeProject', () => JustifyContentBasics);

Align Items #

Adding alignItems to a component's style determines the alignment of children along the secondary axis (if the primary axis is row, then the secondary is column, and vice versa). Should children be aligned at the start, the center, the end, or stretched to fill? Available options are flex-start, center, flex-end, and stretch.

For stretch to have an effect, children must not have a fixed dimension along the secondary axis. In the following example, setting alignItems: stretch does nothing until the width: 50 is removed from the children.

import React, { Component } from 'react'; + +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => JustifyContentBasics);

Align Items #

Adding alignItems to a component's style determines the alignment of children along the secondary axis (if the primary axis is row, then the secondary is column, and vice versa). Should children be aligned at the start, the center, the end, or stretched to fill? Available options are flex-start, center, flex-end, and stretch.

For stretch to have an effect, children must not have a fixed dimension along the secondary axis. In the following example, setting alignItems: stretch does nothing until the width: 50 is removed from the children.

import React, { Component } from 'react'; import { AppRegistry, View } from 'react-native'; -class AlignItemsBasics extends Component { +export default class AlignItemsBasics extends Component { render() { return ( // Try setting `alignItems` to 'flex-start' @@ -57,8 +59,9 @@ class AlignItemsBasics extends ); } }; - -AppRegistry.registerComponent('AwesomeProject', () => AlignItemsBasics);

Going Deeper #

We've covered the basics, but there are many other styles you may need for layouts. The full list of props that control layout is documented here.

We're getting close to being able to build a real application. One thing we are still missing is a way to take user input, so let's move on to learn how to handle text input with the TextInput component.

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file + \ No newline at end of file diff --git a/docs/geolocation.html b/docs/geolocation.html index 6b319143c45..cc04f04df1e 100644 --- a/docs/geolocation.html +++ b/docs/geolocation.html @@ -1,88 +1,27 @@ -Geolocation

Geolocation #

The Geolocation API extends the web spec: +Geolocation

Geolocation #

The Geolocation API extends the web spec: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation

As a browser polyfill, this API is available through the navigator.geolocation -global - you do not need to import it.

iOS #

You need to include the NSLocationWhenInUseUsageDescription key +global - you do not need to import it.

Configuration and Permissions #

+ +

iOS #

You need to include the NSLocationWhenInUseUsageDescription key in Info.plist to enable geolocation when using the app. Geolocation is enabled by default when you create a project with react-native init.

In order to enable geolocation in the background, you need to include the 'NSLocationAlwaysUsageDescription' key in Info.plist and add location as -a background mode in the 'Capabilities' tab in Xcode.

Android #

To request access to location, you need to add the following line to your +a background mode in the 'Capabilities' tab in Xcode.

Android #

To request access to location, you need to add the following line to your app's AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Android API >= 18 Positions will also contain a mocked boolean to indicate if position was created from a mock provider.

Methods #

static getCurrentPosition(geo_success, geo_error?, geo_options?) #

Invokes the success callback once with the latest location info. Supported options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool) On Android, if the location is cached this can return almost immediately, or it will request an update which might take a while.

static watchPosition(success, error?, options?) #

Invokes the success callback whenever the location changes. Supported -options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool), distanceFilter(m)

static clearWatch(watchID) #

static stopObserving() #

You can edit the content above on GitHub and send us a pull request!

Examples #

Edit on GitHub
/* eslint no-console: 0 */ -'use strict'; - - -var React = require('react'); -var ReactNative = require('react-native'); -var { - StyleSheet, - Text, - View, -} = ReactNative; - -exports.framework = 'React'; -exports.title = 'Geolocation'; -exports.description = 'Examples of using the Geolocation API.'; - -exports.examples = [ - { - title: 'navigator.geolocation', - render: function(): React.Element<any> { - return <GeolocationExample />; - }, - } -]; - -class GeolocationExample extends React.Component { - state = { - initialPosition: 'unknown', - lastPosition: 'unknown', - }; - - watchID: ?number = null; - - componentDidMount() { - navigator.geolocation.getCurrentPosition( - (position) => { - var initialPosition = JSON.stringify(position); - this.setState({initialPosition}); - }, - (error) => alert(JSON.stringify(error)), - {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000} - ); - this.watchID = navigator.geolocation.watchPosition((position) => { - var lastPosition = JSON.stringify(position); - this.setState({lastPosition}); - }); - } - - componentWillUnmount() { - navigator.geolocation.clearWatch(this.watchID); - } - - render() { - return ( - <View> - <Text> - <Text style={styles.title}>Initial position: </Text> - {this.state.initialPosition} - </Text> - <Text> - <Text style={styles.title}>Current position: </Text> - {this.state.lastPosition} - </Text> - </View> - ); - } -} - -var styles = StyleSheet.create({ - title: { - fontWeight: '500', - }, -});
\ No newline at end of file + \ No newline at end of file diff --git a/docs/gesture-responder-system.html b/docs/gesture-responder-system.html index 04b7a26673c..b1b7fb37b31 100644 --- a/docs/gesture-responder-system.html +++ b/docs/gesture-responder-system.html @@ -1,4 +1,4 @@ -Gesture Responder System

Gesture Responder System #

The gesture responder system manages the lifecycle of gestures in your app. A touch can go through several phases as the app determines what the user's intention is. For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. This can even change during the duration of a touch. There can also be multiple simultaneous touches.

The touch responder system is needed to allow components to negotiate these touch interactions without any additional knowledge about their parent or child components. This system is implemented in ResponderEventPlugin.js, which contains further details and documentation.

Best Practices #

To make your app feel great, every action should have the following attributes:

  • Feedback/highlighting- show the user what is handling their touch, and what will happen when they release the gesture
  • Cancel-ability- when making an action, the user should be able to abort it mid-touch by dragging their finger away

These features make users more comfortable while using an app, because it allows people to experiment and interact without fear of making mistakes.

TouchableHighlight and Touchable* #

The responder system can be complicated to use. So we have provided an abstract Touchable implementation for things that should be "tappable". This uses the responder system and allows you to easily configure tap interactions declaratively. Use TouchableHighlight anywhere where you would use a button or link on web.

Responder Lifecycle #

A view can become the touch responder by implementing the correct negotiation methods. There are two methods to ask the view if it wants to become responder:

  • View.props.onStartShouldSetResponder: (evt) => true, - Does this view want to become responder on the start of a touch?
  • View.props.onMoveShouldSetResponder: (evt) => true, - Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness?

If the View returns true and attempts to become the responder, one of the following will happen:

  • View.props.onResponderGrant: (evt) => {} - The View is now responding for touch events. This is the time to highlight and show the user what is happening
  • View.props.onResponderReject: (evt) => {} - Something else is the responder right now and will not release it

If the view is responding, the following handlers can be called:

  • View.props.onResponderMove: (evt) => {} - The user is moving their finger
  • View.props.onResponderRelease: (evt) => {} - Fired at the end of the touch, ie "touchUp"
  • View.props.onResponderTerminationRequest: (evt) => true - Something else wants to become responder. Should this view release the responder? Returning true allows release
  • View.props.onResponderTerminate: (evt) => {} - The responder has been taken from the View. Might be taken by other views after a call to onResponderTerminationRequest, or might be taken by the OS without asking (happens with control center/ notification center on iOS)

evt is a synthetic touch event with the following form:

  • nativeEvent
    • changedTouches - Array of all touch events that have changed since the last event
    • identifier - The ID of the touch
    • locationX - The X position of the touch, relative to the element
    • locationY - The Y position of the touch, relative to the element
    • pageX - The X position of the touch, relative to the root element
    • pageY - The Y position of the touch, relative to the root element
    • target - The node id of the element receiving the touch event
    • timestamp - A time identifier for the touch, useful for velocity calculation
    • touches - Array of all current touches on the screen

Capture ShouldSet Handlers #

onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, where the deepest node is called first. That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. This is desirable in most cases, because it makes sure all controls and buttons are usable.

However, sometimes a parent will want to make sure that it becomes responder. This can be handled by using the capture phase. Before the responder system bubbles up from the deepest component, it will do a capture phase, firing on*ShouldSetResponderCapture. So if a parent View wants to prevent the child from becoming responder on a touch start, it should have a onStartShouldSetResponderCapture handler which returns true.

  • View.props.onStartShouldSetResponderCapture: (evt) => true,
  • View.props.onMoveShouldSetResponderCapture: (evt) => true,

PanResponder #

For higher-level gesture interpretation, check out PanResponder.

You can edit the content above on GitHub and send us a pull request!

Gesture Responder System #

The gesture responder system manages the lifecycle of gestures in your app. A touch can go through several phases as the app determines what the user's intention is. For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. This can even change during the duration of a touch. There can also be multiple simultaneous touches.

The touch responder system is needed to allow components to negotiate these touch interactions without any additional knowledge about their parent or child components. This system is implemented in ResponderEventPlugin.js, which contains further details and documentation.

Best Practices #

To make your app feel great, every action should have the following attributes:

  • Feedback/highlighting- show the user what is handling their touch, and what will happen when they release the gesture
  • Cancel-ability- when making an action, the user should be able to abort it mid-touch by dragging their finger away

These features make users more comfortable while using an app, because it allows people to experiment and interact without fear of making mistakes.

TouchableHighlight and Touchable* #

The responder system can be complicated to use. So we have provided an abstract Touchable implementation for things that should be "tappable". This uses the responder system and allows you to easily configure tap interactions declaratively. Use TouchableHighlight anywhere where you would use a button or link on web.

Responder Lifecycle #

A view can become the touch responder by implementing the correct negotiation methods. There are two methods to ask the view if it wants to become responder:

  • View.props.onStartShouldSetResponder: (evt) => true, - Does this view want to become responder on the start of a touch?
  • View.props.onMoveShouldSetResponder: (evt) => true, - Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness?

If the View returns true and attempts to become the responder, one of the following will happen:

  • View.props.onResponderGrant: (evt) => {} - The View is now responding for touch events. This is the time to highlight and show the user what is happening
  • View.props.onResponderReject: (evt) => {} - Something else is the responder right now and will not release it

If the view is responding, the following handlers can be called:

  • View.props.onResponderMove: (evt) => {} - The user is moving their finger
  • View.props.onResponderRelease: (evt) => {} - Fired at the end of the touch, ie "touchUp"
  • View.props.onResponderTerminationRequest: (evt) => true - Something else wants to become responder. Should this view release the responder? Returning true allows release
  • View.props.onResponderTerminate: (evt) => {} - The responder has been taken from the View. Might be taken by other views after a call to onResponderTerminationRequest, or might be taken by the OS without asking (happens with control center/ notification center on iOS)

evt is a synthetic touch event with the following form:

  • nativeEvent
    • changedTouches - Array of all touch events that have changed since the last event
    • identifier - The ID of the touch
    • locationX - The X position of the touch, relative to the element
    • locationY - The Y position of the touch, relative to the element
    • pageX - The X position of the touch, relative to the root element
    • pageY - The Y position of the touch, relative to the root element
    • target - The node id of the element receiving the touch event
    • timestamp - A time identifier for the touch, useful for velocity calculation
    • touches - Array of all current touches on the screen

Capture ShouldSet Handlers #

onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, where the deepest node is called first. That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. This is desirable in most cases, because it makes sure all controls and buttons are usable.

However, sometimes a parent will want to make sure that it becomes responder. This can be handled by using the capture phase. Before the responder system bubbles up from the deepest component, it will do a capture phase, firing on*ShouldSetResponderCapture. So if a parent View wants to prevent the child from becoming responder on a touch start, it should have a onStartShouldSetResponderCapture handler which returns true.

  • View.props.onStartShouldSetResponderCapture: (evt) => true,
  • View.props.onMoveShouldSetResponderCapture: (evt) => true,

PanResponder #

For higher-level gesture interpretation, check out PanResponder.

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file + \ No newline at end of file diff --git a/docs/getting-started.html b/docs/getting-started.html index b1273ed3676..2bcb775fc9f 100644 --- a/docs/getting-started.html +++ b/docs/getting-started.html @@ -1,145 +1,250 @@ -Getting Started

Getting Started #

Welcome to React Native! This page will help you install React Native on -your system, so that you can build apps with it right away. If you already -have React Native installed, you can skip ahead to the -Tutorial.

The instructions are a bit different depending on your development operating system, and whether you want to start developing for iOS or Android. If you -want to develop for both iOS and Android, that's fine - you just have to pick -one to start with, since the setup is a bit different.

- - Mobile OS: - iOS - Android - Development OS: - macOS - Linux - Windows + .toggler ul { + border-bottom: 0; + } + } + .toggler a { + display: inline-block; + padding: 10px 5px; + margin: 2px; + border: 1px solid #05A5D1; + border-radius: 3px; + text-decoration: none !important; + } + .display-guide-quickstart .toggler .button-quickstart, + .display-guide-native .toggler .button-native, + .display-os-mac .toggler .button-mac, + .display-os-linux .toggler .button-linux, + .display-os-windows .toggler .button-windows, + .display-platform-ios .toggler .button-ios, + .display-platform-android .toggler .button-android { + background-color: #05A5D1; + color: white; + } + block { display: none; } + .display-guide-quickstart.display-platform-ios.display-os-mac .quickstart.ios.mac, + .display-guide-quickstart.display-platform-ios.display-os-linux .quickstart.ios.linux, + .display-guide-quickstart.display-platform-ios.display-os-windows .quickstart.ios.windows, + .display-guide-quickstart.display-platform-android.display-os-mac .quickstart.android.mac, + .display-guide-quickstart.display-platform-android.display-os-linux .quickstart.android.linux, + .display-guide-quickstart.display-platform-android.display-os-windows .quickstart.android.windows, .display-guide-native.display-platform-ios.display-os-mac .native.ios.mac, + .display-guide-native.display-platform-ios.display-os-linux .native.ios.linux, + .display-guide-native.display-platform-ios.display-os-windows .native.ios.windows, + .display-guide-native.display-platform-android.display-os-mac .native.android.mac, + .display-guide-native.display-platform-android.display-os-linux .native.android.linux, + .display-guide-native.display-platform-android.display-os-windows .native.android.windows { + display: block; + } + + +

This page will help you install and build your first React Native app. If you already have React Native installed, you can skip ahead to the Tutorial.

+
    + + +
-
+ -

Unsupported #

Unfortunately, Apple only lets you develop for iOS on a Mac. If you want to build an iOS app but you don't have a Mac yet, you can try starting with the Android instructions instead.
+

Create React Native App is the easiest way to start building a new React Native application. It allows you to start a project without installing or configuring any tools to build native code - no Xcode or Android Studio installation required (see Caveats).

Assuming that you have Node installed, you can use npm to install the create-react-native-app command line utility:

npm install -g create-react-native-app

Then run the following commands to create a new React Native project called "AwesomeProject":

create-react-native-app AwesomeProject -
+cd AwesomeProject +npm start

This will start a development server for you, and print a QR code in your terminal.

Running your React Native application #

Install the Expo client app on your iOS or Android phone and connect to the same wireless network as your computer. Using the Expo app, scan the QR code from your terminal to open your project.

Modifying your app #

Now that you have successfully run the app, let's modify it. Open App.js in your text editor of choice and edit some lines. The application should reload automatically once you save your changes.

That's it! #

Congratulations! You've successfully run and modified your first React Native app.

-
+

Now what? #

  • Create React Native App also has a user guide you can reference if you have questions specific to the tool.

  • If you can't get this to work, see the Troubleshooting section in the README for Create React Native App.

If you're curious to learn more about React Native, continue on +to the Tutorial.

Running your app on a simulator or virtual device #

Create React Native App makes it really easy to run your React Native app on a physical device without setting up a development environment. If you want to run your app on the iOS Simulator or an Android Virtual Device, please refer to the instructions for building projects with native code to learn how to install Xcode and set up your Android development environment.

Once you've set these up, you can launch your app on on an Android Virtual Device by running npm run android, or on the iOS Simulator by running npm run ios (macOS only).

Caveats #

Because you don't build any native code when using Create React Native App to create a project, it's not possible to include custom native modules beyond the React Native APIs and components that are available in the Expo client app.

If you know that you'll eventually need to include your own native code, Create React Native App is still a good way to get started. In that case you'll just need to "eject" eventually to create your own native builds. If you do eject, the "Building Projects with Native Code" instructions will be required to continue working on your project.

Create React Native App configures your project to use the most recent React Native version that is supported by the Expo client app. The Expo client app usually gains support for a given React Native version about a week after the React Native version is released as stable. You can check this document to find out what versions are supported.

If you're integrating React Native into an existing project, you'll want to skip Create React Native App and go directly to setting up the native build environment. Select "Building Projects with Native Code" above for instructions on configuring a native build environment for React Native.

-

Installing Dependencies #

You will need Node, Watchman, the React Native command line interface, and Xcode.

+

Follow these instructions if you need to build native code in your project. For example, if you are integrating React Native into an existing application, or if you "ejected" from Create React Native App, you'll need this section.

-

Installing Dependencies #

You will need Node, Watchman, the React Native command line interface, a JDK, and Android Studio.

+

The instructions are a bit different depending on your development operating system, and whether you want to start developing for iOS or Android. If you want to develop for both iOS and Android, that's fine - you just have to pick +one to start with, since the setup is a bit different.

+ Development OS: + macOS + Windows + Linux + Target OS: + iOS + Android +
-

Installing Dependencies #

You will need Node, the React Native command line interface, a JDK, and Android Studio.

+ -

Installing Dependencies #

You will need Node, the React Native command line interface, Python2, a JDK, and Android Studio.

+

Unsupported #

A Mac is required to build projects with native code for iOS. You can follow the Quick Start to learn how to build your app using Create React Native App instead.

+ +
+ +

Installing dependencies #

You will need Node, Watchman, the React Native command line interface, and Xcode.

While you can use any editor of your choice to develop your app, you will need to install Xcode in order to set up the necessary tooling to build your React Native app for iOS.

+ +

Installing dependencies #

You will need Node, Watchman, the React Native command line interface, a JDK, and Android Studio.

+ +

Installing dependencies #

You will need Node, the React Native command line interface, a JDK, and Android Studio.

+ +

Installing dependencies #

You will need Node, the React Native command line interface, Python2, a JDK, and Android Studio.

+ +

While you can use any editor of your choice to develop your app, you will need to install Android Studio in order to set up the necessary tooling to build your React Native app for Android.

Node, Watchman #

We recommend installing Node and Watchman using Homebrew. Run the following commands in a Terminal after installing Homebrew:

brew install node -brew install watchman

If you have already installed Node on your system, make sure it is version 4 or newer.

Watchman is a tool by Facebook for watching changes in the filesystem. It is highly recommended you install it for better performance.

+brew install watchman

If you have already installed Node on your system, make sure it is version 4 or newer.

Watchman is a tool by Facebook for watching changes in the filesystem. It is highly recommended you install it for better performance.

-

Node #

Follow the installation instructions for your Linux distribution to install Node 4 or newer.

+

Node #

Follow the installation instructions for your Linux distribution to install Node 6 or newer.

-

Node, Python2, JDK #

We recommend installing Node and Python2 via Chocolatey, a popular package manager for Windows.

Android Studio, which we will install next, requires a recent version of the Java SE Development Kit (JDK) which can be installed using Chocolatey.

Open a Command Prompt as Administrator, then run:

choco install nodejs.install +

Node, Python2, JDK #

We recommend installing Node and Python2 via Chocolatey, a popular package manager for Windows.

React Native also requires a recent version of the Java SE Development Kit (JDK), as well as Python 2. Both can be installed using Chocolatey.

Open an Administrator Command Prompt (right click Command Prompt and select "Run as Administrator"), then run the following commands:

choco install nodejs.install choco install python2 -choco install jdk8

If you have already installed Node on your system, make sure it is version 4 or newer. If you already have a JDK on your system, make sure it is version 8 or newer.

You can find additional installation options on Node.js's Downloads page.

+choco install jdk8

If you have already installed Node on your system, make sure it is version 4 or newer. If you already have a JDK on your system, make sure it is version 8 or newer.

You can find additional installation options on Node's Downloads page.

-

The React Native CLI #

Node comes with npm, which lets you install the React Native command line interface.

Run the following command in a Terminal:

npm install -g react-native-cli

If you get an error like Cannot find module 'npmlog', try installing npm directly: curl -0 -L https://npmjs.org/install.sh | sudo sh.

+

The React Native CLI #

Node comes with npm, which lets you install the React Native command line interface.

Run the following command in a Terminal:

npm install -g react-native-cli

If you get an error like Cannot find module 'npmlog', try installing npm directly: curl -0 -L https://npmjs.org/install.sh | sudo sh.

-

The React Native CLI #

Node comes with npm, which lets you install the React Native command line interface.

Run the following command in a Terminal:

npm install -g react-native-cli

If you get an error like Cannot find module 'npmlog', try installing npm directly: curl -0 -L https://npmjs.org/install.sh | sudo sh.

+

The React Native CLI #

Node comes with npm, which lets you install the React Native command line interface.

Run the following command in a Command Prompt or shell:

npm install -g react-native-cli

If you get an error like Cannot find module 'npmlog', try installing npm directly: curl -0 -L https://npmjs.org/install.sh | sudo sh.

-

Xcode #

The easiest way to install Xcode is via the Mac App Store. Installing Xcode will also install the iOS Simulator and all the necessary tools to build your iOS app.

If you have already installed Xcode on your system, make sure it is version 8 or higher.

You will also need to install the Xcode Command Line Tools. Open Xcode, then choose "Preferences..." from the Xcode menu. Go to the Locations panel and install the tools by selecting the most recent version in the Command Line Tools dropdown.

Xcode Command Line Tools

+

Xcode #

The easiest way to install Xcode is via the Mac App Store. Installing Xcode will also install the iOS Simulator and all the necessary tools to build your iOS app.

If you have already installed Xcode on your system, make sure it is version 8 or higher.

Command Line Tools #

You will also need to install the Xcode Command Line Tools. Open Xcode, then choose "Preferences..." from the Xcode menu. Go to the Locations panel and install the tools by selecting the most recent version in the Command Line Tools dropdown.

Xcode Command Line Tools

-

Android Development Environment #

Setting up your development environment can be somewhat tedious if you're new to Android development. If you're already familiar with Android development, there are a few things you may need to configure. In either case, please make sure to carefully follow the next few steps.

+

Java Development Kit #

React Native requires a recent version of the Java SE Development Kit (JDK). Download and install JDK 8 or newer if needed.

-

Android Studio requires a recent version of the Java SE Development Kit (JDK). Go ahead and install JDK 8 or newer if needed.

+

Android development environment #

Setting up your development environment can be somewhat tedious if you're new to Android development. If you're already familiar with Android development, there are a few things you may need to configure. In either case, please make sure to carefully follow the next few steps.

-

1. Download and install Android Studio #

Android Studio provides the Android SDK and AVD (emulator) required to run and test your React Native apps. Download Android Studio, then follow the installation instructions. Choose Custom installation when prompted by the Setup Wizard, and proceed to the next step.

+

1. Install Android Studio #

Download and install Android Studio. Choose a "Custom" setup when prompted to select an installation type. Make sure the boxes next to all of the following are checked:

-

2. Install the AVD and HAXM #

Android Virtual Devices allow you to run Android apps on your computer without the need for an actual Android phone or tablet. Choose Custom installation when running Android Studio for the first time. Make sure the boxes next to all of the following are checked:

  • Android SDK
  • Android SDK Platform
  • Performance (Intel ® HAXM)
  • Android Virtual Device

Then, click "Next" to install all of these components.

If you've already installed Android Studio before, you can still install HAXM without performing a custom installation.

+
  • Android SDK
  • Android SDK Platform
  • Performance (Intel ® HAXM)
  • Android Virtual Device
-

2. Install the AVD and configure VM acceleration #

Android Virtual Devices allow you to run Android apps on your computer without the need for an actual Android phone or tablet. Choose Custom installation when running Android Studio for the first time. Make sure the boxes next to all of the following are checked:

  • Android SDK
  • Android SDK Platform
  • Android Virtual Device

Click "Next" to install all of these components, then configure VM acceleration on your system.

+
  • Android SDK
  • Android SDK Platform
  • Android Virtual Device
-

3. Install the Android 6.0 (Marshmallow) SDK #

Android Studio installs the most recent Android SDK by default. React Native, however, requires the Android 6.0 (Marshmallow) SDK. To install it, launch the SDK Manager, click on "Configure" > "SDK Manager" in the "Welcome to Android Studio" screen.

The SDK Manager can also be found within the Android Studio "Preferences" menu, under Appearance & BehaviorSystem SettingsAndroid SDK.

Select the "SDK Platforms" tab from within the SDK Manager, then check the box next to "Show Package Details" in the bottom right corner. Look for and expand the Android 6.0 (Marshmallow) entry, then make sure the following items are all checked:

  • Google APIs
  • Android SDK Platform 23
  • Intel x86 Atom_64 System Image
  • Google APIs Intel x86 Atom_64 System Image

Android SDK Manager

Next, select the "SDK Tools" tab and check the box next to "Show Package Details" here as well. Look for and expand the "Android SDK Build Tools" entry, then make sure that Android SDK Build-Tools 23.0.1 is selected.

Finally, click "Apply" to download and install the Android SDK and related build tools.

+

Then, click "Next" to install all of these components.

If the checkboxes are grayed out, you will have a chance to install these components later on.

Once setup has finalized and you're presented with the Welcome screen, proceed to the next step.

2. Install the Android SDK #

Android Studio installs the latest Android SDK by default. Building a React Native app with native code, however, requires the Android 6.0 (Marshmallow) SDK in particular. Additional Android SDKs can be installed through the SDK Manager in Android Studio.

The SDK Manager can be accessed from the "Welcome to Android Studio" screen. Click on "Configure", then select "SDK Manager".

-

4. Set up the ANDROID_HOME environment variable #

The React Native command line interface requires the ANDROID_HOME environment variable to be set up.

+

Android Studio Welcome

-

Add the following lines to your ~/.profile (or equivalent) config file:

export ANDROID_HOME=${HOME}/Library/Android/sdk -export PATH=${PATH}:${ANDROID_HOME}/tools -export PATH=${PATH}:${ANDROID_HOME}/platform-tools

Type source ~/.profile to load the config into your current shell.

Please make sure you export the correct path for ANDROID_HOME. If you installed the Android SDK using Homebrew, it would be located at /usr/local/opt/android-sdk.

+

Android Studio Welcome

-

Add the following lines to your ~/.profile (or equivalent) config file:

export ANDROID_HOME=${HOME}/Android/Sdk -export PATH=${PATH}:${ANDROID_HOME}/tools -export PATH=${PATH}:${ANDROID_HOME}/platform-tools

Type source ~/.profile to load the config into your current shell.

Please make sure you export the correct path for ANDROID_HOME if you did not install the Android SDK using Android Studio.

+

The SDK Manager can also be found within the Android Studio "Preferences" dialog, under Appearance & BehaviorSystem SettingsAndroid SDK.

Select the "SDK Platforms" tab from within the SDK Manager, then check the box next to "Show Package Details" in the bottom right corner. Look for and expand the Android 6.0 (Marshmallow) entry, then make sure the following items are all checked:

  • Google APIs
  • Android SDK Platform 23
  • Intel x86 Atom_64 System Image
  • Google APIs Intel x86 Atom_64 System Image
-

Go to Control PanelSystem and SecuritySystemChange settings → -Advanced System SettingsEnvironment variablesNew, then enter the path to your Android SDK.

env variable

Restart the Command Prompt to apply the new environment variable.

Please make sure you export the correct path for ANDROID_HOME if you did not install the Android SDK using Android Studio.

+

Android SDK Manager

+ +

Android SDK Manager

+ +

Next, select the "SDK Tools" tab and check the box next to "Show Package Details" here as well. Look for and expand the "Android SDK Build-Tools" entry, then make sure that 23.0.1 is selected.

+ +

Android SDK Manager - 23.0.1 Build Tools

+ +

Android SDK Manager - 23.0.1 Build Tools

+ +

Finally, click "Apply" to download and install the Android SDK and related build tools.

+ +

Android SDK Manager - Installs

+ +

Android SDK Manager - Installs

+ +

3. Configure the ANDROID_HOME environment variable #

The React Native tools require some environment variables to be set up in order to build apps with native code.

+ +

Add the following lines to your $HOME/.bash_profile config file:

+ +
export ANDROID_HOME=$HOME/Library/Android/sdk +export PATH=$PATH:$ANDROID_HOME/tools +export PATH=$PATH:$ANDROID_HOME/platform-tools
+ +
export ANDROID_HOME=$HOME/Android/Sdk +export PATH=$PATH:$ANDROID_HOME/tools +export PATH=$PATH:$ANDROID_HOME/platform-tools
+ +

.bash_profile is specific to bash. If you're using another shell, you will need to edit the appropriate shell-specific config file.

Type source $HOME/.bash_profile to load the config into your current shell. Verify that ANDROID_HOME has been added to your path by running echo $PATH.

Please make sure you use the correct Android SDK path. You can find the actual location of the SDK in the Android Studio "Preferences" dialog, under Appearance & BehaviorSystem SettingsAndroid SDK.

+ +

Open the System pane under System and Security in the Control Panel, then click on Change settings.... Open the Advanced tab and click on Environment Variables.... Click on New... to create a new ANDROID_HOME user variable that points to the path to your Android SDK:

ANDROID_HOME Environment Variable

The SDK is installed, by default, at the following location:

c:\Users\YOUR_USERNAME\AppData\Local\Android\Sdk

You can find the actual location of the SDK in the Android Studio "Preferences" dialog, under Appearance & BehaviorSystem SettingsAndroid SDK.

Open a new Command Prompt window to ensure the new environment variable is loaded before proceeding to the next step.

Watchman (optional) #

Follow the Watchman installation guide to compile and install Watchman from source.

Watchman is a tool by Facebook for watching -changes in the filesystem. It is highly recommended you install it for better performance, but it's alright to skip this if you find the process to be tedious.

+changes in the filesystem. It is highly recommended you install it for better performance, but it's alright to skip this if you find the process to be tedious.

-

Starting the Android Virtual Device #

Android Studio AVD Manager

You can see the list of available AVDs by opening the "AVD Manager" from within Android Studio.

Once in the "AVD Manager", select your AVD and click "Edit...". Choose "Android 6.0 - API Level 23" under Device, and "Intel Atom (x86_64)" under CPU/ABI. Click OK, then select your new AVD and click "Start...", and finally, "Launch".

Android AVD Configuration

It is very common to run into an issue where Android Studio fails to create a default AVD. You may follow the Android Studio User Guide to create a new AVD manually if needed.

Using a real device #

If you have a physical Android device, you can use it for development in place of an AVD. Plug it in to your computer using a USB cable and enable USB debugging before proceeding to the next step.

+

Creating a new application #

Use the React Native command line interface to generate a new React Native project called "AwesomeProject":

react-native init AwesomeProject

This is not necessary if you are integrating React Native into an existing application, if you "ejected" from Create React Native App, or if you're adding iOS support to an existing React Native project (see Platform Specific Code).

-

Testing your React Native Installation #

+

Creating a new application #

Use the React Native command line interface to generate a new React Native project called "AwesomeProject":

react-native init AwesomeProject

This is not necessary if you are integrating React Native into an existing application, if you "ejected" from Create React Native App, or if you're adding Android support to an existing React Native project (see Platform Specific Code).

-

Use the React Native command line interface to generate a new React Native project called "AwesomeProject", then run react-native run-ios inside the newly created folder.

react-native init AwesomeProject -cd AwesomeProject -react-native run-ios

You should see your new app running in the iOS Simulator shortly.

AwesomeProject on iOS

react-native run-ios is just one way to run your app. You can also run it directly from within Xcode or Nuclide.

+

Preparing the Android device #

You will need an Android device to run your React Native Android app. This can be either a physical Android device, or more commonly, you can use an Android Virtual Device which allows you to emulate an Android device on your computer.

Either way, you will need to prepare the device to run Android apps for development.

Using a physical device #

If you have a physical Android device, you can use it for development in place of an AVD by plugging it in to your computer using a USB cable and following the instructions here.

Using a virtual device #

You can see the list of available Android Virtual Devices (AVDs) by opening the "AVD Manager" from within Android Studio. Look for an icon that looks like this:

Android Studio AVD Manager

If you have just installed Android Studio, you will likely need to create a new AVD. Select "Create Virtual Device...", then pick any Phone from the list and click "Next".

-

Use the React Native command line interface to generate a new React Native project called "AwesomeProject", then run react-native run-android inside the newly created folder:

react-native init AwesomeProject -cd AwesomeProject -react-native run-android

If everything is set up correctly, you should see your new app running in your Android emulator shortly.

AwesomeProject on Android

react-native run-android is just one way to run your app - you can also run it directly from within Android Studio or Nuclide.

+

Android Studio AVD Manager

-

Modifying your app #

Now that you have successfully run the app, let's modify it.

+

Android Studio AVD Manager

-
  • Open index.ios.js in your text editor of choice and edit some lines.
  • Hit Command⌘ + R in your iOS Simulator to reload the app and see your change!
+

Select the "x86 Images" tab, then look for the Marshmallow API Level 23, x86_64 ABI image with a Android 6.0 (Google APIs) target.

-
  • Open index.android.js in your text editor of choice and edit some lines.
  • Press the R key twice or select Reload from the Developer Menu to see your change!
+

We recommend configuring VM acceleration on your system to improve performance. Once you've followed those instructions, go back to the AVD Manager.

+ +

Install HAXM

If you don't have HAXM installed, click on "Install HAXM" or follow these instructions to set it up, then go back to the AVD Manager.

AVD List

+ +

Install HAXM

If you don't have HAXM installed, follow these instructions to set it up, then go back to the AVD Manager.

AVD List

+ +

Click "Next" then "Finish" to create your AVD. At this point you should be able to click on the green triangle button next to your AVD to launch it, then proceed to the next step.

+ +

Running your React Native application #

Run react-native run-ios inside your React Native project folder:

cd AwesomeProject +react-native run-ios

You should see your new app running in the iOS Simulator shortly.

AwesomeProject on iOS

react-native run-ios is just one way to run your app. You can also run it directly from within Xcode or Nuclide.

If you can't get this to work, see the Troubleshooting page.

Running on a device #

The above command will automatically run your app on the iOS Simulator by default. If you want to run the app on an actual physical iOS device, please follow the instructions here.

+ +

Running your React Native application #

Run react-native run-android inside your React Native project folder:

cd AwesomeProject +react-native run-android

If everything is set up correctly, you should see your new app running in your Android emulator shortly.

+ +

AwesomeProject on Android

+ +

AwesomeProject on Android

+ +

react-native run-android is just one way to run your app - you can also run it directly from within Android Studio or Nuclide.

If you can't get this to work, see the Troubleshooting page.

+ +

Modifying your app #

Now that you have successfully run the app, let's modify it.

+ +
  • Open index.ios.js in your text editor of choice and edit some lines.
  • Hit ⌘R in your iOS Simulator to reload the app and see your changes!
+ +
  • Open index.android.js in your text editor of choice and edit some lines.
  • Press the R key twice or select Reload from the Developer Menu (⌘M) to see your changes!
+ +

Modifying your app #

Now that you have successfully run the app, let's modify it.

  • Open index.android.js in your text editor of choice and edit some lines.
  • Press the R key twice or select Reload from the Developer Menu (⌘M) to see your changes!

That's it! #

Congratulations! You've successfully run and modified your first React Native app.

-
+ -

Testing your React Native Installation #

Use the React Native command line interface to generate a new React Native project called "AwesomeProject", then run react-native run-android inside the newly created folder:

react-native init AwesomeProject -cd AwesomeProject -react-native run-android
+

That's it! #

Congratulations! You've successfully run and modified your first React Native app.

-

Testing your React Native Installation #

Use the React Native command line interface to generate a new React Native project called "AwesomeProject", then run react-native run-android inside the newly created folder.

react-native init AwesomeProject -cd AwesomeProject -react-native run-android
+ -

If everything is set up correctly, you should see your new app running in your Android emulator shortly.

AwesomeProject on Android

+

Now what? #

  • Turn on Live Reload in the Developer Menu. Your app will now reload automatically whenever you save any changes!

  • If you want to add this new React Native code to an existing application, check out the Integration guide.

If you're curious to learn more about React Native, continue on +to the Tutorial.

-

Modifying your app #

Now that you have successfully run the app, let's modify it.

  • Open index.android.js in your text editor of choice and edit some lines.
  • Press the R key twice or select Reload from the Developer Menu to see your change!

That's it! #

Congratulations! You've successfully run and modified a React Native app.

- -
- -

Now What? #

  • If you want to add this new React Native code to an existing application, check out the Integration guide.

  • If you can't get this to work, see the Troubleshooting page.

  • If you're curious to learn more about React Native, continue on -to the Tutorial.

- -

Now What? #

  • If you want to add this new React Native code to an existing application, check out the Integration guide.

  • If you can't get this to work, see the Troubleshooting page.

  • If you're curious to learn more about React Native, continue on -to the Tutorial.

\ No newline at end of file + \ No newline at end of file diff --git a/docs/handling-text-input.html b/docs/handling-text-input.html index f7221459e7a..d8be77fcd75 100644 --- a/docs/handling-text-input.html +++ b/docs/handling-text-input.html @@ -1,9 +1,9 @@ -Handling Text Input

Handling Text Input #

TextInput is a basic component that allows the user to enter text. It has an onChangeText prop that takes +Handling Text Input

Handling Text Input #

TextInput is a basic component that allows the user to enter text. It has an onChangeText prop that takes a function to be called every time the text changed, and an onSubmitEditing prop that takes a function to be called when the text is submitted.

For example, let's say that as the user types, you're translating their words into a different language. In this new language, every single word is written the same way: 🍕. So the sentence "Hello there Bob" would be translated as "🍕🍕🍕".

import React, { Component } from 'react'; import { AppRegistry, Text, TextInput, View } from 'react-native'; -class PizzaTranslator extends Component { +export default class PizzaTranslator extends Component { constructor(props) { super(props); this.state = {text: ''}; @@ -24,8 +24,9 @@ class PizzaTranslator extends ); } } - -AppRegistry.registerComponent('PizzaTranslator', () => PizzaTranslator);

In this example, we store text in the state, because it changes over time.

There are a lot more things you might want to do with a text input. For example, you could validate the text inside while the user types. For more detailed examples, see the React docs on controlled components, or the reference docs for TextInput.

Text input is probably the simplest example of a component whose state naturally changes over time. Next, let's look at another type of component like this one that controls layout, and learn about the ScrollView.

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file + \ No newline at end of file diff --git a/docs/handling-touches.html b/docs/handling-touches.html index b1d6c8d894c..71fa1e62032 100644 --- a/docs/handling-touches.html +++ b/docs/handling-touches.html @@ -1,4 +1,4 @@ -Handling Touches

Handling Touches #

Users interact with mobile apps mainly through touch. They can use a combination of gestures, such as tapping on a button, scrolling a list, or zooming on a map.

React Native provides components to handle common gestures, such as taps and swipes, as well as a comprehensive gesture responder system to allow for more advanced gesture recognition.

Tappable Components #

You can use "Touchable" components when you want to capture a tapping gesture. They take a function through the onPress props which will be called when the touch begins and ends within the bounds of the component.

Example:

class MyButton extends Component { +Handling Touches

Handling Touches #

Users interact with mobile apps mainly through touch. They can use a combination of gestures, such as tapping on a button, scrolling a list, or zooming on a map.

React Native provides components to handle common gestures, such as taps and swipes, as well as a comprehensive gesture responder system to allow for more advanced gesture recognition.

Tappable Components #

You can use "Touchable" components when you want to capture a tapping gesture. They take a function through the onPress props which will be called when the touch begins and ends within the bounds of the component.

Example:

class MyButton extends Component { _onPressButton() { console.log("You tapped the button!"); } @@ -10,7 +10,7 @@ </TouchableHighlight> ); } -}

Tappable components should provide feedback that show the user what is handling their touch, and what will happen when they lift their finger. The user should also be able to cancel a tap by dragging their finger away.

Which component you use will depend on what kind of feedback you want to provide:

  • Generally, you can use TouchableHighlight anywhere you would use a button or link on web. The view's background will be darkened when the user presses down on the button.

  • You may consider using TouchableNativeFeedback on Android to display ink surface reaction ripples that respond to the user's touch.

  • TouchableOpacity can be used to provide feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down.

  • If you need to handle a tap gesture but you don't want any feedback to be displayed, use TouchableWithoutFeedback.

Long presses #

In some cases, you may want to detect when a user presses and holds a view for a set amount of time. These long presses can be handled by passing a function to the onLongPress props of any of the touchable components listed above.

Scrolling lists and swiping views #

A common pattern to many mobile apps is the scrollable list of items. Users interact with these using panning or swiping gestures. The ScrollView component displays a list of items that can be scrolled using these gestures.

ScrollViews can scroll vertically or horizontally, and can be configured to allow paging through views using swiping gestures by using the pagingEnabled props. Swiping horizontally between views can also be implemented on Android using the ViewPagerAndroid component.

A ListView is a special kind of ScrollView that is best suited for displaying long vertical lists of items. It can also display section headers and footers, similar to UITableViews on iOS.

Pinch-to-zoom #

A ScrollView with a single item can be used to allow the user to zoom content. Set up the maximumZoomScale and minimumZoomScale props and your user will be able to use pinch and expand gestures to zoom in and out.

Handling additional gestures #

If you want to allow a user to drag a view around the screen, or you want to implement your own custom pan/drag gesture, take a look at the PanResponder API or the gesture responder system docs.

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file + \ No newline at end of file diff --git a/docs/headless-js-android.html b/docs/headless-js-android.html index 37fa07e0111..1e7cb657c64 100644 --- a/docs/headless-js-android.html +++ b/docs/headless-js-android.html @@ -1,4 +1,4 @@ -Headless JS

Headless JS #

Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.

The JS API #

A task is a simple async function that you register on AppRegistry, similar to registering React applications:

AppRegistry.registerHeadlessTask('SomeTaskName', () => require('SomeTaskName'));

Then, in SomeTaskName.js:

module.exports = async (taskData) => { +Headless JS

Headless JS #

Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.

The JS API #

A task is a simple async function that you register on AppRegistry, similar to registering React applications:

AppRegistry.registerHeadlessTask('SomeTaskName', () => require('SomeTaskName'));

Then, in SomeTaskName.js:

module.exports = async (taskData) => { // do stuff }

You can do anything in your task as long as it doesn't touch UI: network requests, timers and so on. Once your task completes (i.e. the promise is resolved), React Native will go into "paused" mode (unless there are other tasks running, or there is a foreground app).

The Java API #

Yes, this does still require some native code, but it's pretty thin. You need to extend HeadlessJsTaskService and override getTaskConfig, e.g.:

public class MyTaskService extends HeadlessJsTaskService { @@ -29,6 +29,6 @@ apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/height-and-width.html b/docs/height-and-width.html index 48350e48690..0f89e554d28 100644 --- a/docs/height-and-width.html +++ b/docs/height-and-width.html @@ -1,7 +1,7 @@ -Height and Width

Height and Width #

A component's height and width determine its size on the screen.

Fixed Dimensions #

The simplest way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless, and represent density-independent pixels.

import React, { Component } from 'react'; +Height and Width

Height and Width #

A component's height and width determine its size on the screen.

Fixed Dimensions #

The simplest way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless, and represent density-independent pixels.

import React, { Component } from 'react'; import { AppRegistry, View } from 'react-native'; -class FixedDimensionsBasics extends Component { +export default class FixedDimensionsBasics extends Component { render() { return ( <View> @@ -12,11 +12,12 @@ class FixedDimensionsBasics extends ); } } - -AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);

Setting dimensions this way is common for components that should always render at exactly the same size, regardless of screen dimensions.

Flex Dimensions #

Use flex in a component's style to have the component expand and shrink dynamically based on available space. Normally you will use flex: 1, which tells a component to fill all available space, shared evenly amongst each other component with the same parent. The larger the flex given, the higher the ratio of space a component will take compared to its siblings.

A component can only expand to fill available space if its parent has dimensions greater than 0. If a parent does not have either a fixed width and height or flex, the parent will have dimensions of 0 and the flex children will not be visible.

import React, { Component } from 'react'; + +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);

Setting dimensions this way is common for components that should always render at exactly the same size, regardless of screen dimensions.

Flex Dimensions #

Use flex in a component's style to have the component expand and shrink dynamically based on available space. Normally you will use flex: 1, which tells a component to fill all available space, shared evenly amongst each other component with the same parent. The larger the flex given, the higher the ratio of space a component will take compared to its siblings.

A component can only expand to fill available space if its parent has dimensions greater than 0. If a parent does not have either a fixed width and height or flex, the parent will have dimensions of 0 and the flex children will not be visible.

import React, { Component } from 'react'; import { AppRegistry, View } from 'react-native'; -class FlexDimensionsBasics extends Component { +export default class FlexDimensionsBasics extends Component { render() { return ( // Try removing the `flex: 1` on the parent View. @@ -30,8 +31,9 @@ class FlexDimensionsBasics extends ); } } - -AppRegistry.registerComponent('AwesomeProject', () => FlexDimensionsBasics);

After you can control a component's size, the next step is to learn how to lay it out on the screen.

You can edit the content above on GitHub and send us a pull request!

\ No newline at end of file + \ No newline at end of file diff --git a/docs/image.html b/docs/image.html index c6ca1f483de..055cc1eaa72 100644 --- a/docs/image.html +++ b/docs/image.html @@ -1,10 +1,10 @@ -Image

Image #

A React component for displaying different types of images, +Image

Image #

A React component for displaying different types of images, including network images, static resources, temporary local images, and images from local disk, such as the camera roll.

This example shows both fetching and displaying an image from local storage as well as one from network.

import React, { Component } from 'react'; import { AppRegistry, View, Image } from 'react-native'; -class DisplayAnImage extends Component { +export default class DisplayAnImage extends Component { render() { return ( <View> @@ -20,8 +20,8 @@ class DisplayAnImage extends } } -// App registration and rendering -AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage);

You can also add style to an image:

import React, { Component } from 'react'; +// skip this line if using Create React Native App +AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage);

You can also add style to an image:

import React, { Component } from 'react'; import { AppRegistry, View, Image, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ @@ -31,7 +31,7 @@ const styles = StyleSheet} }); -class DisplayAnImageWithStyle extends Component { +export default class DisplayAnImageWithStyle extends Component { render() { return ( <View> @@ -44,27 +44,27 @@ class DisplayAnImageWithStyle extends } } -// App registration and rendering +// skip these lines if using Create React Native App AppRegistry.registerComponent( 'DisplayAnImageWithStyle', () => DisplayAnImageWithStyle -);

GIF and WebP support on Android #

By default, GIF and WebP are not supported on Android.

You will need to add some optional modules in android/app/build.gradle, depending on the needs of your app.

dependencies { +);

GIF and WebP support on Android #

When building your own native code, GIF and WebP are not supported by default on Android.

You will need to add some optional modules in android/app/build.gradle, depending on the needs of your app.

dependencies { // If your app supports Android versions before Ice Cream Sandwich (API level 14) - compile 'com.facebook.fresco:animated-base-support:0.11.0' + compile 'com.facebook.fresco:animated-base-support:1.0.1' // For animated GIF support - compile 'com.facebook.fresco:animated-gif:0.11.0' + compile 'com.facebook.fresco:animated-gif:1.0.1' // For WebP support, including animated WebP - compile 'com.facebook.fresco:animated-webp:0.11.0' - compile 'com.facebook.fresco:webpsupport:0.11.0' + compile 'com.facebook.fresco:animated-webp:1.0.1' + compile 'com.facebook.fresco:webpsupport:1.0.1' // For WebP support, without animations - compile 'com.facebook.fresco:webpsupport:0.11.0' + compile 'com.facebook.fresco:webpsupport:1.0.1' }

Also, if you use GIF with ProGuard, you will need to add this rule in proguard-rules.pro :

-keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl { public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline.core.ExecutorSupplier); -}

Props #

onError?: function #

Invoked on load error with {nativeEvent: {error}}.

onLayout?: function #

Invoked on mount and layout changes with -{nativeEvent: {layout: {x, y, width, height}}}.

onLoad?: function #

Invoked when load completes successfully.

onLoadEnd?: function #

Invoked when load either succeeds or fails.

onLoadStart?: function #

Invoked on load start.

e.g., onLoadStart={(e) => this.setState({loading: true})}

resizeMode?: enum('cover', 'contain', 'stretch', 'repeat', 'center') #

Determines how to resize the image when the frame doesn't match the raw +}

Props #

onError?: PropTypes.func #

Invoked on load error with {nativeEvent: {error}}.

onLayout?: PropTypes.func #

Invoked on mount and layout changes with +{nativeEvent: {layout: {x, y, width, height}}}.

onLoad?: PropTypes.func #

Invoked when load completes successfully.

onLoadEnd?: PropTypes.func #

Invoked when load either succeeds or fails.

onLoadStart?: PropTypes.func #

Invoked on load start.

e.g., onLoadStart={(e) => this.setState({loading: true})}

resizeMode?: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat', 'center']) #

Determines how to resize the image when the frame doesn't match the raw image dimensions.

  • cover: Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).

  • contain: Scale the image uniformly (maintain the image's aspect ratio) @@ -85,790 +85,43 @@ background and setting the overlayColor to the same color as the background.

    For details of how this works under the hood, see http://frescolib.org/docs/rounded-corners-and-circles.html

ImageResizeMode is an Enum for different image resizing modes, set via the resizeMode style property on Image components. The values are contain, cover, -stretch, center, repeat.

testID?: string #

A unique identifier for this element to be used in UI Automation -testing scripts.

androidresizeMethod?: enum('auto', 'resize', 'scale') #

The mechanism that should be used to resize the image when the image's dimensions +stretch, center, repeat.

testID?: PropTypes.string #

A unique identifier for this element to be used in UI Automation +testing scripts.

androidresizeMethod?: PropTypes.oneOf(['auto', 'resize', 'scale']) #

The mechanism that should be used to resize the image when the image's dimensions differ from the image view's dimensions. Defaults to auto.

  • auto: Use heuristics to pick between resize and scale.

  • resize: A software operation which changes the encoded image in memory before it gets decoded. This should be used instead of scale when the image is much larger than the view.

  • scale: The image gets drawn downscaled or upscaled. Compared to resize, scale is faster (usually hardware accelerated) and produces higher quality images. This should be used if the image is smaller than the view. It should also be used if the -image is slightly bigger than the view.

More details about resize and scale can be found at http://frescolib.org/docs/resizing-rotating.html.

iosaccessibilityLabel?: node #

The text that's read by the screen reader when the user interacts with -the image.

iosaccessible?: bool #

When true, indicates the image is an accessibility element.

iosblurRadius?: number #

blurRadius: the blur radius of the blur filter added to the image

ioscapInsets?: {top: number, left: number, bottom: number, right: number} #

When the image is resized, the corners of the size specified +image is slightly bigger than the view.

More details about resize and scale can be found at http://frescolib.org/docs/resizing-rotating.html.

iosaccessibilityLabel?: PropTypes.node #

The text that's read by the screen reader when the user interacts with +the image.

iosaccessible?: PropTypes.bool #

When true, indicates the image is an accessibility element.

iosblurRadius?: PropTypes.number #

blurRadius: the blur radius of the blur filter added to the image

ioscapInsets?: {top: number, left: number, bottom: number, right: number} #

When the image is resized, the corners of the size specified by capInsets will stay a fixed size, but the center content and borders of the image will be stretched. This is useful for creating resizable rounded buttons, shadows, and other resizable assets. More info in the -official Apple documentation.

iosdefaultSource?: {uri: string, width: number, height: number, scale: number}, number #

A static image to display while loading the image source.

iosdefaultSource?: PropTypes.oneOfType([ + // TODO: Tooling to support documenting these directly and having them display in the docs. + PropTypes.shape({ + uri: PropTypes.string, + width: PropTypes.number, + height: PropTypes.number, + scale: PropTypes.number, + }), + PropTypes.number, +]) #

A static image to display while loading the image source.

  • uri - a string representing the resource identifier for the image, which should be either a local file path or the name of a static image resource (which should be wrapped in the require('./path/to/image.png') function).
  • width, height - can be specified if known at build time, in which case these will be used to set the default <Image/> component dimensions.
  • scale - used to indicate the scale factor of the image. Defaults to 1.0 if -unspecified, meaning that one image pixel equates to one display point / DIP.
  • number - Opaque type returned by something like require('./image.jpg').

iosonPartialLoad?: function #

Invoked when a partial load of the image is complete. The definition of +unspecified, meaning that one image pixel equates to one display point / DIP.

  • number - Opaque type returned by something like require('./image.jpg').
  • iosonPartialLoad?: PropTypes.func #

    Invoked when a partial load of the image is complete. The definition of what constitutes a "partial load" is loader specific though this is meant -for progressive JPEG loads.

    iosonProgress?: function #

    Invoked on download progress with {nativeEvent: {loaded, total}}.

    Methods #

    static getSize(uri: string, success: function, failure: function): #

    Retrieve the width and height (in pixels) of an image prior to displaying it. +for progressive JPEG loads.

    iosonProgress?: PropTypes.func #

    Invoked on download progress with {nativeEvent: {loaded, total}}.

    Methods #

    static getSize(uri: string, success: function, failure?: function): #

    Retrieve the width and height (in pixels) of an image prior to displaying it. This method can fail if the image cannot be found, or fails to download.

    In order to retrieve the image dimensions, the image may first need to be loaded or downloaded, after which it will be cached. This means that in principle you could use this method to preload images, however it is not optimized for that purpose, and may in future be implemented in a way that does not fully load/download the image data. A proper, supported way to preload images will be provided as a separate API.

    Does not work for static image resources.

    Parameters:
    Name and TypeDescription
    uri

    string

    The location of the image.

    success

    function

    The function that will be called if the image was successfully found and width -and height retrieved.

    failure

    function

    The function that will be called if there was an error, such as failing to +and height retrieved.

    [failure]

    function

    The function that will be called if there was an error, such as failing to to retrieve the image.

    static prefetch(url: string): #

    Prefetches a remote image for later use by downloading it to the disk -cache

    Parameters:
    Name and TypeDescription
    url

    string

    The remote location of the image.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - ActivityIndicator, - Image, - Platform, - StyleSheet, - Text, - View, -} = ReactNative; - -var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg=='; - -var ImageCapInsetsExample = require('./ImageCapInsetsExample'); -const IMAGE_PREFETCH_URL = 'http://origami.design/public/images/bird-logo.png?r=1&t=' + Date.now(); -var prefetchTask = Image.prefetch(IMAGE_PREFETCH_URL); - -var NetworkImageCallbackExample = React.createClass({ - getInitialState: function() { - return { - events: [], - startLoadPrefetched: false, - mountTime: new Date(), - }; - }, - - componentWillMount() { - this.setState({mountTime: new Date()}); - }, - - render: function() { - var { mountTime } = this.state; - - return ( - <View> - <Image - source={this.props.source} - style={[styles.base, {overflow: 'visible'}]} - onLoadStart={() => this._loadEventFired(`✔ onLoadStart (+${new Date() - mountTime}ms)`)} - onLoad={(event) => { - // Currently this image source feature is only available on iOS. - if (event.nativeEvent.source) { - const url = event.nativeEvent.source.url; - this._loadEventFired(`✔ onLoad (+${new Date() - mountTime}ms) for URL ${url}`); - } else { - this._loadEventFired(`✔ onLoad (+${new Date() - mountTime}ms)`); - } - }} - onLoadEnd={() => { - this._loadEventFired(`✔ onLoadEnd (+${new Date() - mountTime}ms)`); - this.setState({startLoadPrefetched: true}, () => { - prefetchTask.then(() => { - this._loadEventFired(`✔ Prefetch OK (+${new Date() - mountTime}ms)`); - }, error => { - this._loadEventFired(`✘ Prefetch failed (+${new Date() - mountTime}ms)`); - }); - }); - }} - /> - {this.state.startLoadPrefetched ? - <Image - source={this.props.prefetchedSource} - style={[styles.base, {overflow: 'visible'}]} - onLoadStart={() => this._loadEventFired(`✔ (prefetched) onLoadStart (+${new Date() - mountTime}ms)`)} - onLoad={(event) => { - // Currently this image source feature is only available on iOS. - if (event.nativeEvent.source) { - const url = event.nativeEvent.source.url; - this._loadEventFired(`✔ (prefetched) onLoad (+${new Date() - mountTime}ms) for URL ${url}`); - } else { - this._loadEventFired(`✔ (prefetched) onLoad (+${new Date() - mountTime}ms)`); - } - }} - onLoadEnd={() => this._loadEventFired(`✔ (prefetched) onLoadEnd (+${new Date() - mountTime}ms)`)} - /> - : null} - <Text style={{marginTop: 20}}> - {this.state.events.join('\n')} - </Text> - </View> - ); - }, - - _loadEventFired(event) { - this.setState((state) => { - return state.events = [...state.events, event]; - }); - } -}); - -var NetworkImageExample = React.createClass({ - getInitialState: function() { - return { - error: false, - loading: false, - progress: 0 - }; - }, - render: function() { - var loader = this.state.loading ? - <View style={styles.progress}> - <Text>{this.state.progress}%</Text> - <ActivityIndicator style={{marginLeft:5}} /> - </View> : null; - return this.state.error ? - <Text>{this.state.error}</Text> : - <Image - source={this.props.source} - style={[styles.base, {overflow: 'visible'}]} - onLoadStart={(e) => this.setState({loading: true})} - onError={(e) => this.setState({error: e.nativeEvent.error, loading: false})} - onProgress={(e) => this.setState({progress: Math.round(100 * e.nativeEvent.loaded / e.nativeEvent.total)})} - onLoad={() => this.setState({loading: false, error: false})}> - {loader} - </Image>; - } -}); - -var ImageSizeExample = React.createClass({ - getInitialState: function() { - return { - width: 0, - height: 0, - }; - }, - componentDidMount: function() { - Image.getSize(this.props.source.uri, (width, height) => { - this.setState({width, height}); - }); - }, - render: function() { - return ( - <View style={{flexDirection: 'row'}}> - <Image - style={{ - width: 60, - height: 60, - backgroundColor: 'transparent', - marginRight: 10, - }} - source={this.props.source} /> - <Text> - Actual dimensions:{'\n'} - Width: {this.state.width}, Height: {this.state.height} - </Text> - </View> - ); - }, -}); - -var MultipleSourcesExample = React.createClass({ - getInitialState: function() { - return { - width: 30, - height: 30, - }; - }, - render: function() { - return ( - <View> - <View style={{flexDirection: 'row', justifyContent: 'space-between'}}> - <Text - style={styles.touchableText} - onPress={this.decreaseImageSize} > - Decrease image size - </Text> - <Text - style={styles.touchableText} - onPress={this.increaseImageSize} > - Increase image size - </Text> - </View> - <Text>Container image size: {this.state.width}x{this.state.height} </Text> - <View - style={{height: this.state.height, width: this.state.width}} > - <Image - style={{flex: 1}} - source={[ - {uri: 'https://facebook.github.io/react/img/logo_small.png', width: 38, height: 38}, - {uri: 'https://facebook.github.io/react/img/logo_small_2x.png', width: 76, height: 76}, - {uri: 'https://facebook.github.io/react/img/logo_og.png', width: 400, height: 400} - ]} - /> - </View> - </View> - ); - }, - increaseImageSize: function() { - if (this.state.width >= 100) { - return; - } - this.setState({ - width: this.state.width + 10, - height: this.state.height + 10, - }); - }, - decreaseImageSize: function() { - if (this.state.width <= 10) { - return; - } - this.setState({ - width: this.state.width - 10, - height: this.state.height - 10, - }); - }, -}); - -exports.displayName = (undefined: ?string); -exports.framework = 'React'; -exports.title = '<Image>'; -exports.description = 'Base component for displaying different types of images.'; - -exports.examples = [ - { - title: 'Plain Network Image', - description: 'If the `source` prop `uri` property is prefixed with ' + - '"http", then it will be downloaded from the network.', - render: function() { - return ( - <Image - source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} - style={styles.base} - /> - ); - }, - }, - { - title: 'Plain Static Image', - description: 'Static assets should be placed in the source code tree, and ' + - 'required in the same way as JavaScript modules.', - render: function() { - return ( - <View style={styles.horizontal}> - <Image source={require('./uie_thumb_normal.png')} style={styles.icon} /> - <Image source={require('./uie_thumb_selected.png')} style={styles.icon} /> - <Image source={require('./uie_comment_normal.png')} style={styles.icon} /> - <Image source={require('./uie_comment_highlighted.png')} style={styles.icon} /> - </View> - ); - }, - }, - { - title: 'Image Loading Events', - render: function() { - return ( - <NetworkImageCallbackExample source={{uri: 'http://origami.design/public/images/bird-logo.png?r=1&t=' + Date.now()}} - prefetchedSource={{uri: IMAGE_PREFETCH_URL}}/> - ); - }, - }, - { - title: 'Error Handler', - render: function() { - return ( - <NetworkImageExample source={{uri: 'https://TYPO_ERROR_facebook.github.io/react/img/logo_og.png'}} /> - ); - }, - platform: 'ios', - }, - { - title: 'Image Download Progress', - render: function() { - return ( - <NetworkImageExample source={{uri: 'http://origami.design/public/images/bird-logo.png?r=1'}}/> - ); - }, - platform: 'ios', - }, - { - title: 'defaultSource', - description: 'Show a placeholder image when a network image is loading', - render: function() { - return ( - <Image - defaultSource={require('./bunny.png')} - source={{uri: 'https://facebook.github.io/origami/public/images/birds.jpg'}} - style={styles.base} - /> - ); - }, - platform: 'ios', - }, - { - title: 'Cache Policy', - description: 'First image has never been loaded before and is instructed not to load unless in cache.' + - 'Placeholder image from above will stay. Second image is the same but forced to load regardless of' + - ' local cache state.', - render: function () { - return ( - <View style={styles.horizontal}> - <Image - defaultSource={require('./bunny.png')} - source={{ - uri: smallImage.uri + '?cacheBust=notinCache' + Date.now(), - cache: 'only-if-cached' - }} - style={styles.base} - /> - <Image - defaultSource={require('./bunny.png')} - source={{ - uri: smallImage.uri + '?cacheBust=notinCache' + Date.now(), - cache: 'reload' - }} - style={styles.base} - /> - </View> - ); - }, - platform: 'ios', - }, - { - title: 'Border Color', - render: function() { - return ( - <View style={styles.horizontal}> - <Image - source={smallImage} - style={[ - styles.base, - styles.background, - {borderWidth: 3, borderColor: '#f099f0'} - ]} - /> - </View> - ); - }, - }, - { - title: 'Border Width', - render: function() { - return ( - <View style={styles.horizontal}> - <Image - source={smallImage} - style={[ - styles.base, - styles.background, - {borderWidth: 5, borderColor: '#f099f0'} - ]} - /> - </View> - ); - }, - }, - { - title: 'Border Radius', - render: function() { - return ( - <View style={styles.horizontal}> - <Image - style={[styles.base, {borderRadius: 5}]} - source={fullImage} - /> - <Image - style={[styles.base, styles.leftMargin, {borderRadius: 19}]} - source={fullImage} - /> - </View> - ); - }, - }, - { - title: 'Background Color', - render: function() { - return ( - <View style={styles.horizontal}> - <Image source={smallImage} style={styles.base} /> - <Image - style={[ - styles.base, - styles.leftMargin, - {backgroundColor: 'rgba(0, 0, 100, 0.25)'} - ]} - source={smallImage} - /> - <Image - style={[styles.base, styles.leftMargin, {backgroundColor: 'red'}]} - source={smallImage} - /> - <Image - style={[styles.base, styles.leftMargin, {backgroundColor: 'black'}]} - source={smallImage} - /> - </View> - ); - }, - }, - { - title: 'Opacity', - render: function() { - return ( - <View style={styles.horizontal}> - <Image - style={[styles.base, {opacity: 1}]} - source={fullImage} - /> - <Image - style={[styles.base, styles.leftMargin, {opacity: 0.8}]} - source={fullImage} - /> - <Image - style={[styles.base, styles.leftMargin, {opacity: 0.6}]} - source={fullImage} - /> - <Image - style={[styles.base, styles.leftMargin, {opacity: 0.4}]} - source={fullImage} - /> - <Image - style={[styles.base, styles.leftMargin, {opacity: 0.2}]} - source={fullImage} - /> - <Image - style={[styles.base, styles.leftMargin, {opacity: 0}]} - source={fullImage} - /> - </View> - ); - }, - }, - { - title: 'Nesting', - render: function() { - return ( - <Image - style={{width: 60, height: 60, backgroundColor: 'transparent'}} - source={fullImage}> - <Text style={styles.nestedText}> - React - </Text> - </Image> - ); - }, - }, - { - title: 'Tint Color', - description: 'The `tintColor` style prop changes all the non-alpha ' + - 'pixels to the tint color.', - render: function() { - return ( - <View> - <View style={styles.horizontal}> - <Image - source={require('./uie_thumb_normal.png')} - style={[styles.icon, {borderRadius: 5, tintColor: '#5ac8fa' }]} - /> - <Image - source={require('./uie_thumb_normal.png')} - style={[styles.icon, styles.leftMargin, {borderRadius: 5, tintColor: '#4cd964' }]} - /> - <Image - source={require('./uie_thumb_normal.png')} - style={[styles.icon, styles.leftMargin, {borderRadius: 5, tintColor: '#ff2d55' }]} - /> - <Image - source={require('./uie_thumb_normal.png')} - style={[styles.icon, styles.leftMargin, {borderRadius: 5, tintColor: '#8e8e93' }]} - /> - </View> - <Text style={styles.sectionText}> - It also works with downloaded images: - </Text> - <View style={styles.horizontal}> - <Image - source={smallImage} - style={[styles.base, {borderRadius: 5, tintColor: '#5ac8fa' }]} - /> - <Image - source={smallImage} - style={[styles.base, styles.leftMargin, {borderRadius: 5, tintColor: '#4cd964' }]} - /> - <Image - source={smallImage} - style={[styles.base, styles.leftMargin, {borderRadius: 5, tintColor: '#ff2d55' }]} - /> - <Image - source={smallImage} - style={[styles.base, styles.leftMargin, {borderRadius: 5, tintColor: '#8e8e93' }]} - /> - </View> - </View> - ); - }, - }, - { - title: 'Resize Mode', - description: 'The `resizeMode` style prop controls how the image is ' + - 'rendered within the frame.', - render: function() { - return ( - <View> - {[smallImage, fullImage].map((image, index) => { - return ( - <View key={index}> - <View style={styles.horizontal}> - <View> - <Text style={[styles.resizeModeText]}> - Contain - </Text> - <Image - style={styles.resizeMode} - resizeMode={Image.resizeMode.contain} - source={image} - /> - </View> - <View style={styles.leftMargin}> - <Text style={[styles.resizeModeText]}> - Cover - </Text> - <Image - style={styles.resizeMode} - resizeMode={Image.resizeMode.cover} - source={image} - /> - </View> - </View> - <View style={styles.horizontal}> - <View> - <Text style={[styles.resizeModeText]}> - Stretch - </Text> - <Image - style={styles.resizeMode} - resizeMode={Image.resizeMode.stretch} - source={image} - /> - </View> - { Platform.OS === 'ios' ? - <View style={styles.leftMargin}> - <Text style={[styles.resizeModeText]}> - Repeat - </Text> - <Image - style={styles.resizeMode} - resizeMode={Image.resizeMode.repeat} - source={image} - /> - </View> - : null } - { Platform.OS === 'android' ? - <View style={styles.leftMargin}> - <Text style={[styles.resizeModeText]}> - Center - </Text> - <Image - style={styles.resizeMode} - resizeMode={Image.resizeMode.center} - source={image} - /> - </View> - : null } - </View> - </View> - ); - })} - </View> - ); - }, - }, - { - title: 'Animated GIF', - render: function() { - return ( - <Image - style={styles.gif} - source={{uri: 'https://38.media.tumblr.com/9e9bd08c6e2d10561dd1fb4197df4c4e/tumblr_mfqekpMktw1rn90umo1_500.gif'}} - /> - ); - }, - platform: 'ios', - }, - { - title: 'Base64 image', - render: function() { - return ( - <Image - style={styles.base64} - source={{uri: base64Icon, scale: 3}} - /> - ); - }, - platform: 'ios', - }, - { - title: 'Cap Insets', - description: - 'When the image is resized, the corners of the size specified ' + - 'by capInsets will stay a fixed size, but the center content and ' + - 'borders of the image will be stretched. This is useful for creating ' + - 'resizable rounded buttons, shadows, and other resizable assets.', - render: function() { - return <ImageCapInsetsExample />; - }, - platform: 'ios', - }, - { - title: 'Image Size', - render: function() { - return <ImageSizeExample source={fullImage} />; - }, - }, - { - title: 'MultipleSourcesExample', - description: - 'The `source` prop allows passing in an array of uris, so that native to choose which image ' + - 'to diplay based on the size of the of the target image', - render: function() { - return <MultipleSourcesExample />; - }, - }, - { - title: 'Legacy local image', - description: - 'Images shipped with the native bundle, but not managed ' + - 'by the JS packager', - render: function() { - return ( - <Image - source={{uri: 'legacy_image', width: 120, height: 120}} - /> - ); - }, - }, - { - title: 'Bundled images', - description: - 'Images shipped in a separate native bundle', - render: function() { - return ( - <View style={{flexDirection: 'row'}}> - <Image - source={{ - url: 'ImageInBundle', - bundle: 'UIExplorerBundle', - width: 100, - height: 100, - }} - style={{borderColor: 'yellow', borderWidth: 4}} - /> - <Image - source={{ - url: 'ImageInAssetCatalog', - bundle: 'UIExplorerBundle', - width: 100, - height: 100, - }} - style={{marginLeft: 10, borderColor: 'blue', borderWidth: 4}} - /> - </View> - ); - }, - platform: 'ios', - }, - { - title: 'Blur Radius', - render: function() { - return ( - <View style={styles.horizontal}> - <Image - style={[styles.base,]} - source={fullImage} - blurRadius={0} - /> - <Image - style={[styles.base, styles.leftMargin]} - source={fullImage} - blurRadius={5} - /> - <Image - style={[styles.base, styles.leftMargin]} - source={fullImage} - blurRadius={10} - /> - <Image - style={[styles.base, styles.leftMargin]} - source={fullImage} - blurRadius={15} - /> - <Image - style={[styles.base, styles.leftMargin]} - source={fullImage} - blurRadius={20} - /> - <Image - style={[styles.base, styles.leftMargin]} - source={fullImage} - blurRadius={25} - /> - </View> - ); - }, - }, -]; - -var fullImage = {uri: 'https://facebook.github.io/react/img/logo_og.png'}; -var smallImage = {uri: 'https://facebook.github.io/react/img/logo_small_2x.png'}; - -var styles = StyleSheet.create({ - base: { - width: 38, - height: 38, - }, - progress: { - flex: 1, - alignItems: 'center', - flexDirection: 'row', - width: 100 - }, - leftMargin: { - marginLeft: 10, - }, - background: { - backgroundColor: '#222222' - }, - sectionText: { - marginVertical: 6, - }, - nestedText: { - marginLeft: 12, - marginTop: 20, - backgroundColor: 'transparent', - color: 'white' - }, - resizeMode: { - width: 90, - height: 60, - borderWidth: 0.5, - borderColor: 'black' - }, - resizeModeText: { - fontSize: 11, - marginBottom: 3, - }, - icon: { - width: 15, - height: 15, - }, - horizontal: { - flexDirection: 'row', - }, - gif: { - flex: 1, - height: 200, - }, - base64: { - flex: 1, - height: 50, - resizeMode: 'contain', - }, - touchableText: { - fontWeight: '500', - color: 'blue', - }, -});
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/imageeditor.html b/docs/imageeditor.html index af9e9dc0137..e1700e200c9 100644 --- a/docs/imageeditor.html +++ b/docs/imageeditor.html @@ -1,4 +1,4 @@ -ImageEditor

    ImageEditor #

    Methods #

    static cropImage(uri, cropData, success, failure) #

    Crop the image specified by the URI param. If URI points to a remote +ImageEditor

    ImageEditor #

    Methods #

    static cropImage(uri, cropData, success, failure) #

    Crop the image specified by the URI param. If URI points to a remote image, it will be downloaded automatically. If the image cannot be loaded/downloaded, the failure callback will be called.

    If the cropping process is successful, the resultant cropped image will be stored in the ImageStore, and the URI returned in the success @@ -19,6 +19,6 @@ cropped image from the ImageStore when you are done with it.

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/imagepickerios.html b/docs/imagepickerios.html index 63b2a21e93a..b04ac7366d5 100644 --- a/docs/imagepickerios.html +++ b/docs/imagepickerios.html @@ -1,4 +1,4 @@ -ImagePickerIOS

    ImagePickerIOS #

    Methods #

    static canRecordVideos(callback) #

    static canUseCamera(callback) #

    static openCameraDialog(config, successCallback, cancelCallback) #

    static openSelectDialog(config, successCallback, cancelCallback) #

    You can edit the content above on GitHub and send us a pull request!

    ImagePickerIOS #

    Methods #

    static canRecordVideos(callback) #

    static canUseCamera(callback) #

    static openCameraDialog(config, successCallback, cancelCallback) #

    static openSelectDialog(config, successCallback, cancelCallback) #

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/images.html b/docs/images.html index 009bbd6bfc4..62b0081ca56 100644 --- a/docs/images.html +++ b/docs/images.html @@ -1,4 +1,4 @@ -Images

    Images #

    Static Image Resources #

    React Native provides a unified way of managing images and other media assets in your iOS and Android apps. To add a static image to your app, place it somewhere in your source code tree and reference it like this:

    <Image source={require('./my-icon.png')} />

    The image name is resolved the same way JS modules are resolved. In the example above, the packager will look for my-icon.png in the same folder as the component that requires it. Also, if you have my-icon.ios.png and my-icon.android.png, the packager will pick the correct file for the platform.

    You can also use the @2x and @3x suffixes to provide images for different screen densities. If you have the following file structure:

    . +Images

    Images #

    Static Image Resources #

    React Native provides a unified way of managing images and other media assets in your iOS and Android apps. To add a static image to your app, place it somewhere in your source code tree and reference it like this:

    <Image source={require('./my-icon.png')} />

    The image name is resolved the same way JS modules are resolved. In the example above, the packager will look for my-icon.png in the same folder as the component that requires it. Also, if you have my-icon.ios.png and my-icon.android.png, the packager will pick the correct file for the platform.

    You can also use the @2x and @3x suffixes to provide images for different screen densities. If you have the following file structure:

    . ├── button.js └── img ├── check@2x.png @@ -16,7 +16,15 @@ style={{width: 400, height: 400}} /> // BAD -<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} />

    Cache Control (iOS Only) #

    In some cases you might only want to display an image if it is already in the local cache, i.e. a low resolution placeholder until a higher resolution is available. In other cases you do not care if the image is outdated and are willing to display an outdated image to save bandwidth. The cache source property gives you control over how the network layer interacts with the cache.

    • default: Use the native platforms default strategy.
    • reload: The data for the URL will be loaded from the originating source. +<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} />

    Network Requests for Images #

    If you would like to set such things as the HTTP-Verb, Headers or a Body along with the image request, you may do this by defining these properties on the source object:

    <Image source={{ + uri: 'https://facebook.github.io/react/img/logo_og.png', + method: 'POST', + headers: { + Pragma: 'no-cache' + }, + body: 'Your Body goes here' + }} + style={{width: 400, height: 400}} />

    Cache Control (iOS Only) #

    In some cases you might only want to display an image if it is already in the local cache, i.e. a low resolution placeholder until a higher resolution is available. In other cases you do not care if the image is outdated and are willing to display an outdated image to save bandwidth. The cache source property gives you control over how the network layer interacts with the cache.

    Props #

    dataSource: ListViewDataSource #

    An instance of ListView.DataSource to use

    enableEmptySections?: bool #

    Flag indicating whether empty section headers should be rendered. In the future release +rendering rows.

    Props #

    dataSource?: PropTypes.instanceOf(ListViewDataSource).isRequired #

    An instance of ListView.DataSource to use

    enableEmptySections?: PropTypes.bool #

    Flag indicating whether empty section headers should be rendered. In the future release empty section headers will be rendered by default, and the flag will be deprecated. -If empty sections are not desired to be rendered their indices should be excluded from sectionID object.

    initialListSize: number #

    How many rows to render on initial component mount. Use this to make +If empty sections are not desired to be rendered their indices should be excluded from sectionID object.

    initialListSize?: PropTypes.number.isRequired #

    How many rows to render on initial component mount. Use this to make it so that the first screen worth of data appears at one time instead of -over the course of multiple frames.

    onChangeVisibleRows?: function #

    (visibleRows, changedRows) => void

    Called when the set of visible rows changes. visibleRows maps +over the course of multiple frames.

    onChangeVisibleRows?: PropTypes.func #

    (visibleRows, changedRows) => void

    Called when the set of visible rows changes. visibleRows maps { sectionID: { rowID: true }} for all the visible rows, and changedRows maps { sectionID: { rowID: true | false }} for the rows that have changed their visibility, with true indicating visible, and -false indicating the view has moved out of view.

    onEndReached?: function #

    Called when all rows have been rendered and the list has been scrolled +false indicating the view has moved out of view.

    onEndReached?: PropTypes.func #

    Called when all rows have been rendered and the list has been scrolled to within onEndReachedThreshold of the bottom. The native scroll -event is provided.

    onEndReachedThreshold: number #

    Threshold in pixels (virtual, not physical) for calling onEndReached.

    pageSize: number #

    Number of rows to render per event loop. Note: if your 'rows' are actually +event is provided.

    onEndReachedThreshold?: PropTypes.number.isRequired #

    Threshold in pixels (virtual, not physical) for calling onEndReached.

    pageSize?: PropTypes.number.isRequired #

    Number of rows to render per event loop. Note: if your 'rows' are actually cells, i.e. they don't span the full width of your view (as in the ListViewGridLayoutExample), you should set the pageSize to be a multiple of the number of cells per row, otherwise you're likely to see gaps at -the edge of the ListView as new pages are loaded.

    removeClippedSubviews?: bool #

    A performance optimization for improving scroll perf of +the edge of the ListView as new pages are loaded.

    removeClippedSubviews?: PropTypes.bool #

    A performance optimization for improving scroll perf of large lists, used in conjunction with overflow: 'hidden' on the row -containers. This is enabled by default.

    renderFooter?: function #

    () => renderable

    The header and footer are always rendered (if these props are provided) +containers. This is enabled by default.

    renderFooter?: PropTypes.func #

    () => renderable

    The header and footer are always rendered (if these props are provided) on every render pass. If they are expensive to re-render, wrap them in StaticContainer or other mechanism as appropriate. Footer is always -at the bottom of the list, and header at the top, on every render pass.

    renderHeader?: function #

    renderRow: function #

    (rowData, sectionID, rowID, highlightRow) => renderable

    Takes a data entry from the data source and its ids and should return +at the bottom of the list, and header at the top, on every render pass.

    renderHeader?: PropTypes.func #

    renderRow?: PropTypes.func.isRequired #

    (rowData, sectionID, rowID, highlightRow) => renderable

    Takes a data entry from the data source and its ids and should return a renderable component to be rendered as the row. By default the data is exactly what was put into the data source, but it's also possible to provide custom extractors. ListView can be notified when a row is being highlighted by calling highlightRow(sectionID, rowID). This sets a boolean value of adjacentRowHighlighted in renderSeparator, allowing you to control the separators above and below the highlighted row. The highlighted -state of a row can be reset by calling highlightRow(null).

    renderScrollComponent: function #

    (props) => renderable

    A function that returns the scrollable component in which the list rows -are rendered. Defaults to returning a ScrollView with the given props.

    renderSectionHeader?: function #

    (sectionData, sectionID) => renderable

    If provided, a header is rendered for this section.

    renderSeparator?: function #

    (sectionID, rowID, adjacentRowHighlighted) => renderable

    If provided, a renderable component to be rendered as the separator +state of a row can be reset by calling highlightRow(null).

    renderScrollComponent?: PropTypes.func.isRequired #

    (props) => renderable

    A function that returns the scrollable component in which the list rows +are rendered. Defaults to returning a ScrollView with the given props.

    renderSectionHeader?: PropTypes.func #

    (sectionData, sectionID) => renderable

    If provided, a header is rendered for this section.

    renderSeparator?: PropTypes.func #

    (sectionID, rowID, adjacentRowHighlighted) => renderable

    If provided, a renderable component to be rendered as the separator below each row but not the last row if there is a section header below. Take a sectionID and rowID of the row above and whether its adjacent row -is highlighted.

    scrollRenderAheadDistance: number #

    How early to start rendering rows before they come on screen, in -pixels.

    stickyHeaderIndices: [number] #

    An array of child indices determining which children get docked to the +is highlighted.

    scrollRenderAheadDistance?: PropTypes.number.isRequired #

    How early to start rendering rows before they come on screen, in +pixels.

    stickyHeaderIndices?: PropTypes.arrayOf(PropTypes.number).isRequired #

    An array of child indices determining which children get docked to the top of the screen when scrolling. For example, passing stickyHeaderIndices={[0]} will cause the first child to be fixed to the top of the scroll view. This property is not supported in conjunction -with horizontal={true}.

    stickySectionHeadersEnabled?: bool #

    Makes the sections headers sticky. The sticky behavior means that it +with horizontal={true}.

    stickySectionHeadersEnabled?: PropTypes.bool #

    Makes the sections headers sticky. The sticky behavior means that it will scroll with the content at the top of the section until it reaches the top of the screen, at which point it will stick to the top until it is pushed off the screen by the next section header. This property is @@ -74,146 +74,7 @@ not supported in conjunction with horizontal={true}. Only enabled b default on iOS because of typical platform standards.

    Methods #

    getMetrics() #

    Exports some data, e.g. for perf investigations or analytics.

    scrollTo(...args: Array) #

    Scrolls to a given x, y offset, either immediately or with a smooth animation.

    See ScrollView#scrollTo.

    scrollToEnd(options?: object) #

    If this is a vertical ListView scrolls to the bottom. If this is a horizontal ListView scrolls to the right.

    Use scrollToEnd({animated: true}) for smooth animated scrolling, scrollToEnd({animated: false}) for immediate scrolling. -If no options are passed, animated defaults to true.

    See ScrollView#scrollToEnd.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - Image, - ListView, - TouchableHighlight, - StyleSheet, - Text, - View, -} = ReactNative; - -var UIExplorerPage = require('./UIExplorerPage'); - -var ListViewSimpleExample = React.createClass({ - statics: { - title: '<ListView>', - description: 'Performant, scrollable list of data.' - }, - - getInitialState: function() { - var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); - return { - dataSource: ds.cloneWithRows(this._genRows({})), - }; - }, - - _pressData: ({}: {[key: number]: boolean}), - - componentWillMount: function() { - this._pressData = {}; - }, - - render: function() { - return ( - <UIExplorerPage - title={this.props.navigator ? null : '<ListView>'} - noSpacer={true} - noScroll={true}> - <ListView - dataSource={this.state.dataSource} - renderRow={this._renderRow} - renderSeparator={this._renderSeparator} - /> - </UIExplorerPage> - ); - }, - - _renderRow: function(rowData: string, sectionID: number, rowID: number, highlightRow: (sectionID: number, rowID: number) => void) { - var rowHash = Math.abs(hashCode(rowData)); - var imgSource = THUMB_URLS[rowHash % THUMB_URLS.length]; - return ( - <TouchableHighlight onPress={() => { - this._pressRow(rowID); - highlightRow(sectionID, rowID); - }}> - <View> - <View style={styles.row}> - <Image style={styles.thumb} source={imgSource} /> - <Text style={styles.text}> - {rowData + ' - ' + LOREM_IPSUM.substr(0, rowHash % 301 + 10)} - </Text> - </View> - </View> - </TouchableHighlight> - ); - }, - - _genRows: function(pressData: {[key: number]: boolean}): Array<string> { - var dataBlob = []; - for (var ii = 0; ii < 100; ii++) { - var pressedText = pressData[ii] ? ' (pressed)' : ''; - dataBlob.push('Row ' + ii + pressedText); - } - return dataBlob; - }, - - _pressRow: function(rowID: number) { - this._pressData[rowID] = !this._pressData[rowID]; - this.setState({dataSource: this.state.dataSource.cloneWithRows( - this._genRows(this._pressData) - )}); - }, - - _renderSeparator: function(sectionID: number, rowID: number, adjacentRowHighlighted: bool) { - return ( - <View - key={`${sectionID}-${rowID}`} - style={{ - height: adjacentRowHighlighted ? 4 : 1, - backgroundColor: adjacentRowHighlighted ? '#3B5998' : '#CCCCCC', - }} - /> - ); - } -}); - -var THUMB_URLS = [ - require('./Thumbnails/like.png'), - require('./Thumbnails/dislike.png'), - require('./Thumbnails/call.png'), - require('./Thumbnails/fist.png'), - require('./Thumbnails/bandaged.png'), - require('./Thumbnails/flowers.png'), - require('./Thumbnails/heart.png'), - require('./Thumbnails/liking.png'), - require('./Thumbnails/party.png'), - require('./Thumbnails/poke.png'), - require('./Thumbnails/superlike.png'), - require('./Thumbnails/victory.png'), - ]; -var LOREM_IPSUM = 'Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix civibus corrumpit referrentur. Te nam case ludus inciderint, te mea facilisi adipiscing. Sea id integre luptatum. In tota sale consequuntur nec. Erat ocurreret mei ei. Eu paulo sapientem vulputate est, vel an accusam intellegam interesset. Nam eu stet pericula reprimique, ea vim illud modus, putant invidunt reprehendunt ne qui.'; - -/* eslint no-bitwise: 0 */ -var hashCode = function(str) { - var hash = 15; - for (var ii = str.length - 1; ii >= 0; ii--) { - hash = ((hash << 5) - hash) + str.charCodeAt(ii); - } - return hash; -}; - -var styles = StyleSheet.create({ - row: { - flexDirection: 'row', - justifyContent: 'center', - padding: 10, - backgroundColor: '#F6F6F6', - }, - thumb: { - width: 64, - height: 64, - }, - text: { - flex: 1, - }, -}); - -module.exports = ListViewSimpleExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/listviewdatasource.html b/docs/listviewdatasource.html index b83769cc022..e1a241dced8 100644 --- a/docs/listviewdatasource.html +++ b/docs/listviewdatasource.html @@ -1,4 +1,4 @@ -ListViewDataSource

    ListViewDataSource #

    Provides efficient data processing and access to the +ListViewDataSource

    ListViewDataSource #

    Provides efficient data processing and access to the ListView component. A ListViewDataSource is created with functions for extracting data from the input blob, and comparing elements (with default implementations for convenience). The input blob can be as simple as an @@ -54,6 +54,6 @@ or null for out of range indexes.

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/modal.html b/docs/modal.html index a236f6550d7..72cd5c6d548 100644 --- a/docs/modal.html +++ b/docs/modal.html @@ -1,4 +1,4 @@ -Modal

    Modal #

    The Modal component is a simple way to present content above an enclosing view.

    Note: If you need more control over how to present modals over the rest of your app, +Modal

    Modal #

    The Modal component is a simple way to present content above an enclosing view.

    Note: If you need more control over how to present modals over the rest of your app, then consider using a top-level Navigator.

    import React, { Component } from 'react'; import { Modal, Text, TouchableHighlight, View } from 'react-native'; @@ -44,212 +44,9 @@ class ModalExample extends /View> ); } -}

    Props #

    animated?: bool #

    Deprecated

    Use the animationType prop instead.

    animationType?: enum('none', 'slide', 'fade') #

    The animationType prop controls how the modal animates.

    • slide slides in from the bottom
    • fade fades into view
    • none appears without an animation

    Default is set to none.

    onShow?: function #

    The onShow prop allows passing a function that will be called once the modal has been shown.

    transparent?: bool #

    The transparent prop determines whether your modal will fill the entire view. Setting this to true will render the modal over a transparent background.

    visible?: bool #

    The visible prop determines whether your modal is visible.

    androidhardwareAccelerated?: bool #

    The hardwareAccelerated prop controls whether to force hardware acceleration for the underlying window.

    androidonRequestClose?: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func #

    The onRequestClose callback is called when the user taps the hardware back button.

    iosonOrientationChange?: function #

    The onOrientationChange callback is called when the orientation changes while the modal is being displayed. -The orientation provided is only 'portrait' or 'landscape'. This callback is also called on initial render, regardless of the current orientation.

    iossupportedOrientations?: [enum('portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right')] #

    The supportedOrientations prop allows the modal to be rotated to any of the specified orientations. -On iOS, the modal is still restricted by what's specified in your app's Info.plist's UISupportedInterfaceOrientations field.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - Modal, - Picker, - StyleSheet, - Switch, - Text, - TouchableHighlight, - View, -} = ReactNative; - -const Item = Picker.Item; - -exports.displayName = (undefined: ?string); -exports.framework = 'React'; -exports.title = '<Modal>'; -exports.description = 'Component for presenting modal views.'; - -class Button extends React.Component { - state = { - active: false, - }; - - _onHighlight = () => { - this.setState({active: true}); - }; - - _onUnhighlight = () => { - this.setState({active: false}); - }; - - render() { - var colorStyle = { - color: this.state.active ? '#fff' : '#000', - }; - return ( - <TouchableHighlight - onHideUnderlay={this._onUnhighlight} - onPress={this.props.onPress} - onShowUnderlay={this._onHighlight} - style={[styles.button, this.props.style]} - underlayColor="#a9d9d4"> - <Text style={[styles.buttonText, colorStyle]}>{this.props.children}</Text> - </TouchableHighlight> - ); - } -} - -const supportedOrientationsPickerValues = [ - ['portrait'], - ['landscape'], - ['landscape-left'], - ['portrait', 'landscape-right'], - ['portrait', 'landscape'], - [], -]; - -class ModalExample extends React.Component { - state = { - animationType: 'none', - modalVisible: false, - transparent: false, - selectedSupportedOrientation: 0, - currentOrientation: 'unknown', - }; - - _setModalVisible = (visible) => { - this.setState({modalVisible: visible}); - }; - - _setAnimationType = (type) => { - this.setState({animationType: type}); - }; - - _toggleTransparent = () => { - this.setState({transparent: !this.state.transparent}); - }; - - render() { - var modalBackgroundStyle = { - backgroundColor: this.state.transparent ? 'rgba(0, 0, 0, 0.5)' : '#f5fcff', - }; - var innerContainerTransparentStyle = this.state.transparent - ? {backgroundColor: '#fff', padding: 20} - : null; - var activeButtonStyle = { - backgroundColor: '#ddd' - }; - - return ( - <View> - <Modal - animationType={this.state.animationType} - transparent={this.state.transparent} - visible={this.state.modalVisible} - onRequestClose={() => this._setModalVisible(false)} - supportedOrientations={supportedOrientationsPickerValues[this.state.selectedSupportedOrientation]} - onOrientationChange={evt => this.setState({currentOrientation: evt.nativeEvent.orientation})} - > - <View style={[styles.container, modalBackgroundStyle]}> - <View style={[styles.innerContainer, innerContainerTransparentStyle]}> - <Text>This modal was presented {this.state.animationType === 'none' ? 'without' : 'with'} animation.</Text> - <Text>It is currently displayed in {this.state.currentOrientation} mode.</Text> - <Button - onPress={this._setModalVisible.bind(this, false)} - style={styles.modalButton}> - Close - </Button> - </View> - </View> - </Modal> - <View style={styles.row}> - <Text style={styles.rowTitle}>Animation Type</Text> - <Button onPress={this._setAnimationType.bind(this, 'none')} style={this.state.animationType === 'none' ? activeButtonStyle : {}}> - none - </Button> - <Button onPress={this._setAnimationType.bind(this, 'slide')} style={this.state.animationType === 'slide' ? activeButtonStyle : {}}> - slide - </Button> - <Button onPress={this._setAnimationType.bind(this, 'fade')} style={this.state.animationType === 'fade' ? activeButtonStyle : {}}> - fade - </Button> - </View> - - <View style={styles.row}> - <Text style={styles.rowTitle}>Transparent</Text> - <Switch value={this.state.transparent} onValueChange={this._toggleTransparent} /> - </View> - - <View> - <Text style={styles.rowTitle}>Supported orientations</Text> - <Picker - selectedValue={this.state.selectedSupportedOrientation} - onValueChange={(_, i) => this.setState({selectedSupportedOrientation: i})} - itemStyle={styles.pickerItem} - > - <Item label="Portrait" value={0} /> - <Item label="Landscape" value={1} /> - <Item label="Landscape left" value={2} /> - <Item label="Portrait and landscape right" value={3} /> - <Item label="Portrait and landscape" value={4} /> - <Item label="Default supportedOrientations" value={5} /> - </Picker> - </View> - - <Button onPress={this._setModalVisible.bind(this, true)}> - Present - </Button> - </View> - ); - } -} - -exports.examples = [ - { - title: 'Modal Presentation', - description: 'Modals can be presented with or without animation', - render: () => <ModalExample />, - }, -]; - -var styles = StyleSheet.create({ - container: { - flex: 1, - justifyContent: 'center', - padding: 20, - }, - innerContainer: { - borderRadius: 10, - alignItems: 'center', - }, - row: { - alignItems: 'center', - flex: 1, - flexDirection: 'row', - marginBottom: 20, - }, - rowTitle: { - flex: 1, - fontWeight: 'bold', - }, - button: { - borderRadius: 5, - flexGrow: 1, - height: 44, - alignSelf: 'stretch', - justifyContent: 'center', - overflow: 'hidden', - }, - buttonText: { - fontSize: 18, - margin: 5, - textAlign: 'center', - }, - modalButton: { - marginTop: 10, - }, - pickerItem: { - fontSize: 16, - }, -});
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/more-resources.html b/docs/more-resources.html index c4436d3634e..e971f3cf652 100644 --- a/docs/more-resources.html +++ b/docs/more-resources.html @@ -1,4 +1,4 @@ -More Resources

    More Resources #

    If you just read through this website, you should be able to build a pretty cool React Native app. But React Native isn't just a product made by one company - it's a community of thousands of developers. So if you're interested in React Native, here's some related stuff you might want to check out.

    Popular Libraries #

    If you're using React Native, you probably already know about React. So I feel a bit silly mentioning this. But if you haven't, check out React - it's the best way to build a modern website.

    One common question is how to handle the "state" of your React Native application. The most popular library for this is Redux. Don't be afraid of how often Redux uses the word "reducer" - it's a pretty simple library, and there's also a nice series of videos explaining it.

    If you're looking for a library that does a specific thing, check out Awesome React Native, a curated list of components that also has demos, articles, and other stuff.

    Example Apps #

    There are some example apps in the Examples/ directory on GitHub. You can run the apps on a simulator or device, and you can see the source code for these apps, which is neat.

    The folks who built the app for Facebook's F8 conference in 2016 also open-sourced the code and wrote up a detailed series of tutorials. This is useful if you want a more in-depth example that's more realistic than most sample apps out there.

    Development Tools #

    Nuclide is the IDE that Facebook uses internally for React Native development. The killer feature of Nuclide is its debugging ability. It also has great inline Flow support.

    Create React Native App makes it significantly easier to get started with a React Native project. There's no need to use Xcode or Android Studio, and you can develop for your iOS device using Linux or Windows.

    Ignite is a starter kit that uses Redux and a few different common UI libraries. It has a CLI to generate apps, components, and containers. If you like all of the individual tech choices, Ignite could be perfect for you.

    CodePush is a service from Microsoft that makes it easy to deploy live updates to your React Native app. If you don't like going through the app store process to deploy little tweaks, and you also don't like setting up your own backend, give CodePush a try.

    Expo is a development environment plus application that focuses on letting you build React Native apps in the Expo development environment, without ever touching Xcode or Android Studio. If you wish React Native was even more JavaScripty and webby, check out Expo.

    Deco is an all-in-one development environment specifically designed for React Native. It can automatically set up a new project, search for open source components, and insert them. You can also tweak your app graphically in real time. Check it out if you use macOS.

    Where React Native People Hang Out #

    The React Native Community Facebook group has thousands of developers, and it's pretty active. Come there to show off your project, or ask how other people solved similar problems.

    Reactiflux is a Discord chat where a lot of React-related discussion happens, including React Native. Discord is just like Slack except it works better for open source projects with a zillion contributors. Check out the #react-native channel.

    The React Twitter account covers both React and React Native. Follow the React Native Twitter account and blog to find out what's happening in the world of React Native.

    There are a lot of React Native Meetups that happen around the world. Often there is React Native content in React meetups as well.

    Sometimes we have React conferences. We posted the videos from React.js Conf 2016, and we'll probably have more conferences in the future, too. Stay tuned.

    You can edit the content above on GitHub and send us a pull request!

    More Resources #

    If you just read through this website, you should be able to build a pretty cool React Native app. But React Native isn't just a product made by one company - it's a community of thousands of developers. So if you're interested in React Native, here's some related stuff you might want to check out.

    Popular Libraries #

    If you're using React Native, you probably already know about React. So I feel a bit silly mentioning this. But if you haven't, check out React - it's the best way to build a modern website.

    One common question is how to handle the "state" of your React Native application. The most popular library for this is Redux. Don't be afraid of how often Redux uses the word "reducer" - it's a pretty simple library, and there's also a nice series of videos explaining it.

    If you're looking for a library that does a specific thing, check out Awesome React Native, a curated list of components that also has demos, articles, and other stuff.

    Example Apps #

    There are some example apps in the Examples/ directory on GitHub. You can run the apps on a simulator or device, and you can see the source code for these apps, which is neat.

    The folks who built the app for Facebook's F8 conference in 2016 also open-sourced the code and wrote up a detailed series of tutorials. This is useful if you want a more in-depth example that's more realistic than most sample apps out there.

    Development Tools #

    Nuclide is the IDE that Facebook uses internally for React Native development. The killer feature of Nuclide is its debugging ability. It also has great inline Flow support.

    Ignite is a starter kit that uses Redux and a few different common UI libraries. It has a CLI to generate apps, components, and containers. If you like all of the individual tech choices, Ignite could be perfect for you.

    CodePush is a service from Microsoft that makes it easy to deploy live updates to your React Native app. If you don't like going through the app store process to deploy little tweaks, and you also don't like setting up your own backend, give CodePush a try.

    Expo is a development environment plus application that focuses on letting you build React Native apps in the Expo development environment, without ever touching Xcode or Android Studio. If you wish React Native was even more JavaScripty and webby, check out Expo.

    Deco is an all-in-one development environment specifically designed for React Native. It can automatically set up a new project, search for open source components, and insert them. You can also tweak your app graphically in real time. Check it out if you use macOS.

    Where React Native People Hang Out #

    The React Native Community Facebook group has thousands of developers, and it's pretty active. Come there to show off your project, or ask how other people solved similar problems.

    Reactiflux is a Discord chat where a lot of React-related discussion happens, including React Native. Discord is just like Slack except it works better for open source projects with a zillion contributors. Check out the #react-native channel.

    The React Twitter account covers both React and React Native. Follow the React Native Twitter account and blog to find out what's happening in the world of React Native.

    There are a lot of React Native Meetups that happen around the world. Often there is React Native content in React meetups as well.

    Sometimes we have React conferences. We posted the videos from React.js Conf 2016, and we'll probably have more conferences in the future, too. Stay tuned.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/native-components-android.html b/docs/native-components-android.html index 3991c522bd5..c73df05d98f 100644 --- a/docs/native-components-android.html +++ b/docs/native-components-android.html @@ -1,4 +1,4 @@ -Native UI Components

    Native UI Components #

    There are tons of native UI widgets out there ready to be used in the latest apps - some of them are part of the platform, others are available as third-party libraries, and still more might be in use in your very own portfolio. React Native has several of the most critical platform components already wrapped, like ScrollView and TextInput, but not all of them, and certainly not ones you might have written yourself for a previous app. Fortunately, it's quite easy to wrap up these existing components for seamless integration with your React Native application.

    Like the native module guide, this too is a more advanced guide that assumes you are somewhat familiar with Android SDK programming. This guide will show you how to build a native UI component, walking you through the implementation of a subset of the existing ImageViewcomponent available in the core React Native library.

    ImageView example #

    For this example we are going to walk through the implementation requirements to allow the use of ImageViews in JavaScript.

    Native views are created and manipulated by extending ViewManager or more commonly SimpleViewManager . A SimpleViewManager is convenient in this case because it applies common properties such as background color, opacity, and Flexbox layout.

    These subclasses are essentially singletons - only one instance of each is created by the bridge. They vend native views to the NativeViewHierarchyManager, which delegates back to them to set and update the properties of the views as necessary. The ViewManagers are also typically the delegates for the views, sending events back to JavaScript via the bridge.

    Vending a view is simple:

    1. Create the ViewManager subclass.
    2. Implement the createViewInstance method
    3. Expose view property setters using @ReactProp (or @ReactPropGroup) annotation
    4. Register the manager in createViewManagers of the applications package.
    5. Implement the JavaScript module

    1. Create the ViewManager subclass #

    In this example we create view manager class ReactImageManager that extends SimpleViewManager of type ReactImageView. ReactImageView is the type of object managed by the manager, this will be the custom native view. Name returned by getName is used to reference the native view type from JavaScript.

    ... +Native UI Components

    Native UI Components #

    There are tons of native UI widgets out there ready to be used in the latest apps - some of them are part of the platform, others are available as third-party libraries, and still more might be in use in your very own portfolio. React Native has several of the most critical platform components already wrapped, like ScrollView and TextInput, but not all of them, and certainly not ones you might have written yourself for a previous app. Fortunately, it's quite easy to wrap up these existing components for seamless integration with your React Native application.

    Like the native module guide, this too is a more advanced guide that assumes you are somewhat familiar with Android SDK programming. This guide will show you how to build a native UI component, walking you through the implementation of a subset of the existing ImageViewcomponent available in the core React Native library.

    ImageView example #

    For this example we are going to walk through the implementation requirements to allow the use of ImageViews in JavaScript.

    Native views are created and manipulated by extending ViewManager or more commonly SimpleViewManager . A SimpleViewManager is convenient in this case because it applies common properties such as background color, opacity, and Flexbox layout.

    These subclasses are essentially singletons - only one instance of each is created by the bridge. They vend native views to the NativeViewHierarchyManager, which delegates back to them to set and update the properties of the views as necessary. The ViewManagers are also typically the delegates for the views, sending events back to JavaScript via the bridge.

    Vending a view is simple:

    1. Create the ViewManager subclass.
    2. Implement the createViewInstance method
    3. Expose view property setters using @ReactProp (or @ReactPropGroup) annotation
    4. Register the manager in createViewManagers of the applications package.
    5. Implement the JavaScript module

    1. Create the ViewManager subclass #

    In this example we create view manager class ReactImageManager that extends SimpleViewManager of type ReactImageView. ReactImageView is the type of object managed by the manager, this will be the custom native view. Name returned by getName is used to reference the native view type from JavaScript.

    ... public class ReactImageManager extends SimpleViewManager<ReactImageView> { @@ -98,6 +98,6 @@ MyCustomView.propTypes \ No newline at end of file + \ No newline at end of file diff --git a/docs/native-components-ios.html b/docs/native-components-ios.html index f1473e624f0..86f51cbbb34 100644 --- a/docs/native-components-ios.html +++ b/docs/native-components-ios.html @@ -1,4 +1,4 @@ -Native UI Components

    Native UI Components #

    There are tons of native UI widgets out there ready to be used in the latest apps - some of them are part of the platform, others are available as third-party libraries, and still more might be in use in your very own portfolio. React Native has several of the most critical platform components already wrapped, like ScrollView and TextInput, but not all of them, and certainly not ones you might have written yourself for a previous app. Fortunately, it's quite easy to wrap up these existing components for seamless integration with your React Native application.

    Like the native module guide, this too is a more advanced guide that assumes you are somewhat familiar with iOS programming. This guide will show you how to build a native UI component, walking you through the implementation of a subset of the existing MapView component available in the core React Native library.

    iOS MapView example #

    Let's say we want to add an interactive Map to our app - might as well use MKMapView, we just need to make it usable from JavaScript.

    Native views are created and manipulated by subclasses of RCTViewManager. These subclasses are similar in function to view controllers, but are essentially singletons - only one instance of each is created by the bridge. They vend native views to the RCTUIManager, which delegates back to them to set and update the properties of the views as necessary. The RCTViewManagers are also typically the delegates for the views, sending events back to JavaScript via the bridge.

    Vending a view is simple:

    • Create the basic subclass.
    • Add the RCT_EXPORT_MODULE() marker macro.
    • Implement the -(UIView *)view method.
    // RNTMapManager.m +Native UI Components

    Native UI Components #

    There are tons of native UI widgets out there ready to be used in the latest apps - some of them are part of the platform, others are available as third-party libraries, and still more might be in use in your very own portfolio. React Native has several of the most critical platform components already wrapped, like ScrollView and TextInput, but not all of them, and certainly not ones you might have written yourself for a previous app. Fortunately, it's quite easy to wrap up these existing components for seamless integration with your React Native application.

    Like the native module guide, this too is a more advanced guide that assumes you are somewhat familiar with iOS programming. This guide will show you how to build a native UI component, walking you through the implementation of a subset of the existing MapView component available in the core React Native library.

    iOS MapView example #

    Let's say we want to add an interactive Map to our app - might as well use MKMapView, we just need to make it usable from JavaScript.

    Native views are created and manipulated by subclasses of RCTViewManager. These subclasses are similar in function to view controllers, but are essentially singletons - only one instance of each is created by the bridge. They vend native views to the RCTUIManager, which delegates back to them to set and update the properties of the views as necessary. The RCTViewManagers are also typically the delegates for the views, sending events back to JavaScript via the bridge.

    Vending a view is simple:

    • Create the basic subclass.
    • Add the RCT_EXPORT_MODULE() marker macro.
    • Implement the -(UIView *)view method.
    // RNTMapManager.m #import <MapKit/MapKit.h> #import <React/RCTViewManager.h> @@ -189,14 +189,15 @@ MapView.propTypes }

    You can see we're adding an event handler property to the view by subclassing MKMapView. Then we're exposing the onChange event handler property and setting the manager as the delegate for every view that it vends. Finally, in the delegate method -mapView:regionDidChangeAnimated: the event handler block is called on the corresponding view with the region data. Calling the onChange event handler block results in calling the same callback prop in JavaScript. This callback is invoked with the raw event, which we typically process in the wrapper component to make a simpler API:

    // MapView.js class MapView extends React.Component { - constructor() { + constructor(props) { + super(props) this._onChange = this._onChange.bind(this); } _onChange(event: Event) { if (!this.props.onRegionChange) { return; } - this.props.onRegionChange(event.nativeEvent.region); + this.props.onRegionChange(event.nativeEvent); } render() { return <RNTMap {...this.props} onChange={this._onChange} />; @@ -206,9 +207,31 @@ MapView.propTypes /** * Callback that is called continuously when the user is dragging the map. */ - onRegionChange: React.PropTypes.func, + onChange: React.PropTypes.func, ... -};

    Styles #

    Since all our native react views are subclasses of UIView, most style attributes will work like you would expect out of the box. Some components will want a default style, however, for example UIDatePicker which is a fixed size. This default style is important for the layout algorithm to work as expected, but we also want to be able to override the default style when using the component. DatePickerIOS does this by wrapping the native component in an extra view, which has flexible styling, and using a fixed style (which is generated with constants passed in from native) on the inner native component:

    // DatePickerIOS.ios.js +}; + +class MapViewExample extends React.Component { + onRegionChange(event: Event) { + // Do stuff with event.region.latitude, etc. + } + + render() { + var region = { + latitude: 37.48, + longitude: -122.16, + latitudeDelta: 0.1, + longitudeDelta: 0.1, + }; + + return ( + <MapView region={region} pitchEnabled={false} style={{flex: 1}} onChange={this.onRegionChange}/> + ); + } +} + +// Module name +AppRegistry.registerComponent('MapViewExample', () => MapViewExample);

    Styles #

    Since all our native react views are subclasses of UIView, most style attributes will work like you would expect out of the box. Some components will want a default style, however, for example UIDatePicker which is a fixed size. This default style is important for the layout algorithm to work as expected, but we also want to be able to override the default style when using the component. DatePickerIOS does this by wrapping the native component in an extra view, which has flexible styling, and using a fixed style (which is generated with constants passed in from native) on the inner native component:

    // DatePickerIOS.ios.js import { UIManager } from 'react-native'; var RCTDatePickerIOSConsts = UIManager.RCTDatePicker.Constants; @@ -263,6 +286,6 @@ import { UIManager \ No newline at end of file + \ No newline at end of file diff --git a/docs/native-modules-android.html b/docs/native-modules-android.html index faaac130423..81a682e1865 100644 --- a/docs/native-modules-android.html +++ b/docs/native-modules-android.html @@ -1,4 +1,4 @@ -Native Modules

    Native Modules #

    Sometimes an app needs access to a platform API that React Native doesn't have a corresponding module for yet. Maybe you want to reuse some existing Java code without having to reimplement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions.

    We designed React Native such that it is possible for you to write real native code and have access to the full power of the platform. This is a more advanced feature and we don't expect it to be part of the usual development process, however it is essential that it exists. If React Native doesn't support a native feature that you need, you should be able to build it yourself.

    Enable Gradle #

    If you plan to make changes in Java code, we recommend enabling Gradle Daemon to speed up builds.

    The Toast Module #

    This guide will use the Toast example. Let's say we would like to be able to create a toast message from JavaScript.

    We start by creating a native module. A native module is a Java class that usually extends the ReactContextBaseJavaModule class and implements the functionality required by the JavaScript. Our goal here is to be able to write ToastAndroid.show('Awesome', ToastAndroid.SHORT); from JavaScript to display a short toast on the screen.

    package com.facebook.react.modules.toast; +Native Modules

    Native Modules #

    Sometimes an app needs access to a platform API that React Native doesn't have a corresponding module for yet. Maybe you want to reuse some existing Java code without having to reimplement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions.

    We designed React Native such that it is possible for you to write real native code and have access to the full power of the platform. This is a more advanced feature and we don't expect it to be part of the usual development process, however it is essential that it exists. If React Native doesn't support a native feature that you need, you should be able to build it yourself.

    Enable Gradle #

    If you plan to make changes in Java code, we recommend enabling Gradle Daemon to speed up builds.

    The Toast Module #

    This guide will use the Toast example. Let's say we would like to be able to create a toast message from JavaScript.

    We start by creating a native module. A native module is a Java class that usually extends the ReactContextBaseJavaModule class and implements the functionality required by the JavaScript. Our goal here is to be able to write ToastAndroid.show('Awesome', ToastAndroid.SHORT); from JavaScript to display a short toast on the screen.

    package com.facebook.react.modules.toast; import android.widget.Toast; @@ -267,6 +267,6 @@ public void onHostDestroy \ No newline at end of file + \ No newline at end of file diff --git a/docs/native-modules-ios.html b/docs/native-modules-ios.html index 563075ad16b..3c937b2ef56 100644 --- a/docs/native-modules-ios.html +++ b/docs/native-modules-ios.html @@ -1,4 +1,4 @@ -Native Modules

    Native Modules #

    Sometimes an app needs access to platform API, and React Native doesn't have a corresponding module yet. Maybe you want to reuse some existing Objective-C, Swift or C++ code without having to reimplement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions.

    We designed React Native such that it is possible for you to write real native code and have access to the full power of the platform. This is a more advanced feature and we don't expect it to be part of the usual development process, however it is essential that it exists. If React Native doesn't support a native feature that you need, you should be able to build it yourself.

    This is a more advanced guide that shows how to build a native module. It assumes the reader knows Objective-C or Swift and core libraries (Foundation, UIKit).

    iOS Calendar Module Example #

    This guide will use the iOS Calendar API example. Let's say we would like to be able to access the iOS calendar from JavaScript.

    A native module is just an Objective-C class that implements the RCTBridgeModule protocol. If you are wondering, RCT is an abbreviation of ReaCT.

    // CalendarManager.h +Native Modules

    Native Modules #

    Sometimes an app needs access to platform API, and React Native doesn't have a corresponding module yet. Maybe you want to reuse some existing Objective-C, Swift or C++ code without having to reimplement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions.

    We designed React Native such that it is possible for you to write real native code and have access to the full power of the platform. This is a more advanced feature and we don't expect it to be part of the usual development process, however it is essential that it exists. If React Native doesn't support a native feature that you need, you should be able to build it yourself.

    This is a more advanced guide that shows how to build a native module. It assumes the reader knows Objective-C or Swift and core libraries (Foundation, UIKit).

    iOS Calendar Module Example #

    This guide will use the iOS Calendar API example. Let's say we would like to be able to access the iOS calendar from JavaScript.

    A native module is just an Objective-C class that implements the RCTBridgeModule protocol. If you are wondering, RCT is an abbreviation of ReaCT.

    // CalendarManager.h #import <React/RCTBridgeModule.h> @interface CalendarManager : NSObject <RCTBridgeModule> @@ -32,7 +32,7 @@ CalendarManager.}

    But by using the automatic type conversion feature, we can skip the manual conversion step completely, and just write:

    RCT_EXPORT_METHOD(addEvent:(NSString *)name location:(NSString *)location date:(NSDate *)date) { // Date is ready to use! -}

    You would then call this from JavaScript by using either:

    CalendarManager.addEvent('Birthday Party', '4 Privet Drive, Surrey', date.getTime()); // passing date as number of seconds since Unix epoch

    or

    CalendarManager.addEvent('Birthday Party', '4 Privet Drive, Surrey', date.toISOString()); // passing date as ISO-8601 string

    And both values would get converted correctly to the native NSDate. A bad value, like an Array, would generate a helpful "RedBox" error message.

    As CalendarManager.addEvent method gets more and more complex, the number of arguments will grow. Some of them might be optional. In this case it's worth considering changing the API a little bit to accept a dictionary of event attributes, like this:

    #import <React/RCTConvert.h> +}

    You would then call this from JavaScript by using either:

    CalendarManager.addEvent('Birthday Party', '4 Privet Drive, Surrey', date.getTime()); // passing date as number of milliseconds since Unix epoch

    or

    CalendarManager.addEvent('Birthday Party', '4 Privet Drive, Surrey', date.toISOString()); // passing date as ISO-8601 string

    And both values would get converted correctly to the native NSDate. A bad value, like an Array, would generate a helpful "RedBox" error message.

    As CalendarManager.addEvent method gets more and more complex, the number of arguments will grow. Some of them might be optional. In this case it's worth considering changing the API a little bit to accept a dictionary of event attributes, like this:

    #import <React/RCTConvert.h> RCT_EXPORT_METHOD(addEvent:(NSString *)name details:(NSDictionary *)details) { @@ -54,7 +54,7 @@ CalendarManager.this.setState({events: events}); } })

    A native module should invoke its callback exactly once. It's okay to store the callback and invoke it later. This pattern is often used to wrap iOS APIs that require delegates - see RCTAlertManager for an example. If the callback is never invoked, some memory is leaked. If both onSuccess and onFail callbacks are passed, you should only invoke one of them.

    If you want to pass error-like objects to JavaScript, use RCTMakeError from RCTUtils.h. Right now this just passes an Error-shaped dictionary to JavaScript, but we would like to automatically generate real JavaScript Error objects in the future.

    Promises #

    Native modules can also fulfill a promise, which can simplify your code, especially when using ES2016's async/await syntax. When the last parameters of a bridged native method are an RCTPromiseResolveBlock and RCTPromiseRejectBlock, its corresponding JS method will return a JS Promise object.

    Refactoring the above code to use a promise instead of callbacks looks like this:

    RCT_REMAP_METHOD(findEvents, - resolver:(RCTPromiseResolveBlock)resolve + findEventsWithResolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { NSArray *events = ... @@ -207,6 +207,6 @@ class CalendarManager \ No newline at end of file + \ No newline at end of file diff --git a/docs/nativemethodsmixin.html b/docs/nativemethodsmixin.html index 6f6c77aeffb..85a26bf812c 100644 --- a/docs/nativemethodsmixin.html +++ b/docs/nativemethodsmixin.html @@ -1,4 +1,4 @@ -NativeMethodsMixin

    NativeMethodsMixin #

    //* +NativeMethodsMixin

    NativeMethodsMixin #

    //* NativeMethodsMixin provides methods to access the underlying native component directly. This can be useful in cases when you want to focus a view or measure its on-screen dimensions, for example.

    The methods described here are available on most of the default components @@ -39,6 +39,6 @@ will depend on the platform and type of view.

    < apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/navigation.html b/docs/navigation.html index cc318d53c84..33df4fd3c05 100644 --- a/docs/navigation.html +++ b/docs/navigation.html @@ -1,11 +1,11 @@ -Navigation

    Navigation #

    This guide covers the various navigation components available in React Native. If you are just getting started with navigation, you will probably want to use React Navigation. React Navigation provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. As this is a JavaScript implementation, it provides the greatest amount of configurability as well as flexibility when integrating with state management libraries such as redux.

    If you're only targeting iOS, you may want to also check out NavigatorIOS as a way of providing a native look and feel with minimal configuration, as it provides a wrapper around the native UINavigationController class. This component will not work on Android, however.

    If you'd like to achieve a native look and feel on both iOS and Android, or you're integrating React Native into an app that already manages navigation natively, the following libraries provide native navigation on both platforms: native-navigation, react-native-navigation.

    React Navigation #

    The community solution to navigation is a standalone library that allows developers to set up the screens of an app with just a few lines of code.

    The first step is to install in your app:

    npm install --save react-navigation

    Then you can quickly create an app with a home screen and a profile screen:

    import { +Navigation

    Navigation #

    This guide covers the various navigation components available in React Native. If you are just getting started with navigation, you will probably want to use React Navigation. React Navigation provides an easy to use navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both iOS and Android. As this is a JavaScript implementation, it provides the greatest amount of configurability as well as flexibility when integrating with state management libraries such as redux.

    If you're only targeting iOS, you may want to also check out NavigatorIOS as a way of providing a native look and feel with minimal configuration, as it provides a wrapper around the native UINavigationController class. This component will not work on Android, however.

    If you'd like to achieve a native look and feel on both iOS and Android, or you're integrating React Native into an app that already manages navigation natively, the following libraries provide native navigation on both platforms: native-navigation, react-native-navigation.

    React Navigation #

    The community solution to navigation is a standalone library that allows developers to set up the screens of an app with just a few lines of code.

    The first step is to install in your project:

    npm install --save react-navigation

    Then you can quickly create an app with a home screen and a profile screen:

    import { StackNavigator, } from 'react-navigation'; const App = StackNavigator({ - Main: {screen: MainScreen}, - Profile: {screen: ProfileScreen}, -});

    Each screen component can set navigation options such as the header title. It can use action creators on the navigation prop to link to other screens:

    class MainScreen extends React.Component { + Home: { screen: HomeScreen }, + Profile: { screen: ProfileScreen }, +});

    Each screen component can set navigation options such as the header title. It can use action creators on the navigation prop to link to other screens:

    class HomeScreen extends React.Component { static navigationOptions = { title: 'Welcome', }; @@ -15,21 +15,22 @@ const App = Sta <Button title="Go to Jane's profile" onPress={() => - navigate('Profile', { name: 'Jane' }); + navigate('Profile', { name: 'Jane' }) } /> ); } -}

    React Navigation routers make it easy to override navigation logic or integrate it into redux. Because routers can be nested inside each other, developers can override navigation logic for one area of the app without making widespread changes.

    The views in React Navigation use native components and the Animated library to deliver 60fps animations that are run on the native thread. Plus, the animations and gestures can be easily customized.

    For a complete intro to React Navigation, follow the getting started guide, or browse other docs such as the intro to navigators.

    Navigator #

    Like React Navigation, Navigator provides a JavaScript implementation of a navigation stack, so it works on both iOS and Android and is easy to customize. Navigator was released alongside React Native in 2015, so it predates the Animated library with native-thread animations.

    Navigator can be adapted to render different components based on the current route in its renderScene function. It will transition new scenes onto the screen by sliding in from the right by default, but you can control this behavior by using the configureScene function. You can also configure a navigation bar through the navigationBar prop.

    Check out the Navigator API reference for specific examples that cover each of these scenarios.

    NavigatorIOS #

    If you are targeting iOS only, you may also want to consider using NavigatorIOS. It looks and feels just like UINavigationController, because it is actually built on top of it.

    <NavigatorIOS +}

    React Navigation routers make it easy to override navigation logic or integrate it into redux. Because routers can be nested inside each other, developers can override navigation logic for one area of the app without making widespread changes.

    The views in React Navigation use native components and the Animated library to deliver 60fps animations that are run on the native thread. Plus, the animations and gestures can be easily customized.

    For a complete intro to React Navigation, follow the React Navigation Getting Started Guide, or browse other docs such as the Intro to Navigators.

    NavigatorIOS #

    NavigatorIOS looks and feels just like UINavigationController, because it is actually built on top of it.

    <NavigatorIOS initialRoute={{ component: MyScene, title: 'My Initial Scene', passProps: { myProp: 'foo' }, }} -/>

    Like other navigation systems, NavigatorIOS uses routes to represent screens, with some important differences. The actual component that will be rendered can be specified using the component key in the route, and any props that should be passed to this component can be specified in passProps. A "navigator" object is automatically passed as a prop to the component, allowing you to call push and pop as needed.

    As NavigatorIOS leverages native UIKit navigation, it will automatically render a navigation bar with a back button and title.

    import React, { Component, PropTypes } from 'react'; -import { NavigatorIOS, Text, TouchableHighlight, View } from 'react-native'; +/>

    Like other navigation systems, NavigatorIOS uses routes to represent screens, with some important differences. The actual component that will be rendered can be specified using the component key in the route, and any props that should be passed to this component can be specified in passProps. A "navigator" object is automatically passed as a prop to the component, allowing you to call push and pop as needed.

    As NavigatorIOS leverages native UIKit navigation, it will automatically render a navigation bar with a back button and title.

    import React from 'react'; +import PropTypes from 'prop-types'; +import { Button, NavigatorIOS, Text, View } from 'react-native'; -export default class NavigatorIOSApp extends Component { +export default class NavigatorIOSApp extends React.Component { render() { return ( <NavigatorIOS @@ -43,7 +44,7 @@ export default class NavigatorIOSApp exten } } -class MyScene extends Component { +class MyScene extends React.Component { static propTypes = { title: PropTypes.string.isRequired, navigator: PropTypes.object.isRequired, @@ -64,13 +65,14 @@ class MyScene extends return ( <View> <Text>Current Scene: { this.props.title }</Text> - <TouchableHighlight onPress={this._onForward}> - <Text>Tap me to load the next scene</Text> - </TouchableHighlight> + <Button + onPress={this._onForward} + title="Tap me to load the next scene" + /> </View> ) } -}

    Check out the NavigatorIOS reference docs to learn more about this component.

    You may also want to check out react-native-navigation, a component that aims to provide native navigation on both iOS and Android.

    NavigationExperimental #

    Since early 2016, React Native has shipped with an experimental re-implementation of the original Navigator component called CardStack. The major benefit it had over Navigator is the smooth native-thread animations provided by the Animated library.

    Because NavigationExperimental only included view components, it required a lot of boilerplate to use by itself. Several libraries sprung up around it, making it easier to use. Libraries such as react-native-router-flux and ex-navigation wrapped NavigationExperimental views in an easier-to-use API. Authors of many of these libraries now support React Navigation.

    The CardStack and other NavigationExperimental views live on as a part of the React Navigation project. The new library aims to be easy to use, while continuing to enable the smooth and customizable animations that NavigationExperimental pioneered.

    As of React Native 0.43, NavigationExperimental is deprecated. It will be removed from the codebase in a later version.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/navigatorios.html b/docs/navigatorios.html index 72d2e2d63e9..299662e8c5f 100644 --- a/docs/navigatorios.html +++ b/docs/navigatorios.html @@ -1,9 +1,9 @@ -NavigatorIOS

    NavigatorIOS #

    NavigatorIOS is a wrapper around +NavigatorIOS

    NavigatorIOS #

    NavigatorIOS is a wrapper around UINavigationController, enabling you to implement a navigation stack. It works exactly the same as it would on a native app using UINavigationController, providing the same animations and behavior from UIKIt.

    As the name implies, it is only available on iOS. Take a look at -React Navigation for a cross-platform +React Navigation for a cross-platform solution in JavaScript, or check out either of these components for native solutions: native-navigation, react-native-navigation.

    To set up the navigator, provide the initialRoute prop with a route @@ -130,311 +130,147 @@ passed to the NavigatorIOS component.

    /> ); }

    In the example above the navigation bar color is changed when the new route -is pushed.

    Props #

    barTintColor?: string #

    The default background color of the navigation bar.

    initialRoute: {component: function, title: string, titleImage: Image.propTypes.source, passProps: object, backButtonIcon: Image.propTypes.source, backButtonTitle: string, leftButtonIcon: Image.propTypes.source, leftButtonTitle: string, leftButtonSystemIcon: Object.keys(SystemIcons), onLeftButtonPress: function, rightButtonIcon: Image.propTypes.source, rightButtonTitle: string, rightButtonSystemIcon: Object.keys(SystemIcons), onRightButtonPress: function, wrapperStyle: ViewPropTypes.style, navigationBarHidden: bool, shadowHidden: bool, tintColor: string, barTintColor: string, titleTextColor: string, translucent: bool} #

    NavigatorIOS uses route objects to identify child views, their props, +is pushed.

    Props #

    barTintColor?: PropTypes.string #

    The default background color of the navigation bar.

    initialRoute?: PropTypes.shape({ + /** + * The React Class to render for this route + */ + component: PropTypes.func.isRequired, + + /** + * The title displayed in the navigation bar and the back button for this + * route. + */ + title: PropTypes.string.isRequired, + + /** + * If set, a title image will appear instead of the text title. + */ + titleImage: Image.propTypes.source, + + /** + * Use this to specify additional props to pass to the rendered + * component. `NavigatorIOS` will automatically pass in `route` and + * `navigator` props to the comoponent. + */ + passProps: PropTypes.object, + + /** + * If set, the left navigation button image will be displayed using this + * source. Note that this doesn't apply to the header of the current + * view, but to those views that are subsequently pushed. + */ + backButtonIcon: Image.propTypes.source, + + /** + * If set, the left navigation button text will be set to this. Note that + * this doesn't apply to the left button of the current view, but to + * those views that are subsequently pushed + */ + backButtonTitle: PropTypes.string, + + /** + * If set, the left navigation button image will be displayed using + * this source. + */ + leftButtonIcon: Image.propTypes.source, + + /** + * If set, the left navigation button will display this text. + */ + leftButtonTitle: PropTypes.string, + + /** + * If set, the left header button will appear with this system icon + * + * Supported icons are `done`, `cancel`, `edit`, `save`, `add`, + * `compose`, `reply`, `action`, `organize`, `bookmarks`, `search`, + * `refresh`, `stop`, `camera`, `trash`, `play`, `pause`, `rewind`, + * `fast-forward`, `undo`, `redo`, and `page-curl` + */ + leftButtonSystemIcon: PropTypes.oneOf(Object.keys(SystemIcons)), + + /** + * This function will be invoked when the left navigation bar item is + * pressed. + */ + onLeftButtonPress: PropTypes.func, + + /** + * If set, the right navigation button image will be displayed using + * this source. + */ + rightButtonIcon: Image.propTypes.source, + + /** + * If set, the right navigation button will display this text. + */ + rightButtonTitle: PropTypes.string, + + /** + * If set, the right header button will appear with this system icon + * + * See leftButtonSystemIcon for supported icons + */ + rightButtonSystemIcon: PropTypes.oneOf(Object.keys(SystemIcons)), + + /** + * This function will be invoked when the right navigation bar item is + * pressed. + */ + onRightButtonPress: PropTypes.func, + + /** + * Styles for the navigation item containing the component. + */ + wrapperStyle: ViewPropTypes.style, + + /** + * Boolean value that indicates whether the navigation bar is hidden. + */ + navigationBarHidden: PropTypes.bool, + + /** + * Boolean value that indicates whether to hide the 1px hairline + * shadow. + */ + shadowHidden: PropTypes.bool, + + /** + * The color used for the buttons in the navigation bar. + */ + tintColor: PropTypes.string, + + /** + * The background color of the navigation bar. + */ + barTintColor: PropTypes.string, + + /** + * The text color of the navigation bar title. + */ + titleTextColor: PropTypes.string, + + /** + * Bboolean value that indicates whether the navigation bar is + * translucent. + */ + translucent: PropTypes.bool, + +}).isRequired #

    NavigatorIOS uses route objects to identify child views, their props, and navigation bar configuration. Navigation operations such as push -operations expect routes to look like this the initialRoute.

    interactivePopGestureEnabled?: bool #

    Boolean value that indicates whether the interactive pop gesture is +operations expect routes to look like this the initialRoute.

    interactivePopGestureEnabled?: PropTypes.bool #

    Boolean value that indicates whether the interactive pop gesture is enabled. This is useful for enabling/disabling the back swipe navigation gesture.

    If this prop is not provided, the default behavior is for the back swipe gesture to be enabled when the navigation bar is shown and disabled when the navigation bar is hidden. Once you've provided the interactivePopGestureEnabled prop, you can never restore the default behavior.

    itemWrapperStyle?: ViewPropTypes.style #

    The default wrapper style for components in the navigator. -A common use case is to set the backgroundColor for every scene.

    navigationBarHidden?: bool #

    Boolean value that indicates whether the navigation bar is hidden -by default.

    shadowHidden?: bool #

    Boolean value that indicates whether to hide the 1px hairline shadow -by default.

    tintColor?: string #

    The default color used for the buttons in the navigation bar.

    titleTextColor?: string #

    The default text color of the navigation bar title.

    translucent?: bool #

    Boolean value that indicates whether the navigation bar is +A common use case is to set the backgroundColor for every scene.

    navigationBarHidden?: PropTypes.bool #

    Boolean value that indicates whether the navigation bar is hidden +by default.

    shadowHidden?: PropTypes.bool #

    Boolean value that indicates whether to hide the 1px hairline shadow +by default.

    tintColor?: PropTypes.string #

    The default color used for the buttons in the navigation bar.

    titleTextColor?: PropTypes.string #

    The default text color of the navigation bar title.

    translucent?: PropTypes.bool #

    Boolean value that indicates whether the navigation bar is translucent by default

    Methods #

    push(route: object) #

    Navigate forward to a new route.

    Parameters:
    Name and TypeDescription
    route

    object

    The new route to navigate to.

    popN(n: number) #

    Go back N scenes at once. When N=1, behavior matches pop().

    Parameters:
    Name and TypeDescription
    n

    number

    The number of scenes to pop.

    pop() #

    Pop back to the previous scene.

    replaceAtIndex(route: object, index: number) #

    Replace a route in the navigation stack.

    Parameters:
    Name and TypeDescription
    route

    object

    The new route that will replace the specified one.

    index

    number

    The route into the stack that should be replaced. If it is negative, it counts from the back of the stack.

    replace(route: object) #

    Replace the route for the current scene and immediately -load the view for the new route.

    Parameters:
    Name and TypeDescription
    route

    object

    The new route to navigate to.

    replacePrevious(route: object) #

    Replace the route/view for the previous scene.

    Parameters:
    Name and TypeDescription
    route

    object

    The new route to will replace the previous scene.

    popToTop() #

    Go back to the topmost item in the navigation stack.

    popToRoute(route: object) #

    Go back to the item for a particular route object.

    Parameters:
    Name and TypeDescription
    route

    object

    The new route to navigate to.

    replacePreviousAndPop(route: object) #

    Replaces the previous route/view and transitions back to it.

    Parameters:
    Name and TypeDescription
    route

    object

    The new route that replaces the previous scene.

    resetTo(route: object) #

    Replaces the top item and pop to it.

    Parameters:
    Name and TypeDescription
    route

    object

    The new route that will replace the topmost item.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -const React = require('react'); -const ReactNative = require('react-native'); -const ViewExample = require('./ViewExample'); - -const createExamplePage = require('./createExamplePage'); -const nativeImageSource = require('nativeImageSource'); -const { - AlertIOS, - NavigatorIOS, - ScrollView, - StyleSheet, - Text, - TouchableHighlight, - View, -} = ReactNative; - -class EmptyPage extends React.Component { - render() { - return ( - <View style={styles.emptyPage}> - <Text style={styles.emptyPageText}> - {this.props.text} - </Text> - </View> - ); - } -} - -class NavigatorIOSExamplePage extends React.Component { - render() { - var recurseTitle = 'Recurse Navigation'; - if (!this.props.depth || this.props.depth === 1) { - recurseTitle += ' - more examples here'; - } - return ( - <ScrollView style={styles.list}> - <View style={styles.line}/> - <View style={styles.group}> - {this._renderRow(recurseTitle, () => { - this.props.navigator.push({ - title: NavigatorIOSExample.title, - component: NavigatorIOSExamplePage, - backButtonTitle: 'Custom Back', - passProps: {depth: this.props.depth ? this.props.depth + 1 : 1}, - }); - })} - {this._renderRow('Push View Example', () => { - this.props.navigator.push({ - title: 'Very Long Custom View Example Title', - component: createExamplePage(null, ViewExample), - }); - })} - {this._renderRow('Custom title image Example', () => { - this.props.navigator.push({ - title: 'Custom title image Example', - titleImage: require('./relay.png'), - component: createExamplePage(null, ViewExample), - }); - })} - {this._renderRow('Custom Right Button', () => { - this.props.navigator.push({ - title: NavigatorIOSExample.title, - component: EmptyPage, - rightButtonTitle: 'Cancel', - onRightButtonPress: () => this.props.navigator.pop(), - passProps: { - text: 'This page has a right button in the nav bar', - } - }); - })} - {this._renderRow('Custom Right System Button', () => { - this.props.navigator.push({ - title: NavigatorIOSExample.title, - component: EmptyPage, - rightButtonSystemIcon: 'bookmarks', - onRightButtonPress: () => this.props.navigator.pop(), - passProps: { - text: 'This page has a right system button in the nav bar', - } - }); - })} - {this._renderRow('Custom Left & Right Icons', () => { - this.props.navigator.push({ - title: NavigatorIOSExample.title, - component: EmptyPage, - leftButtonTitle: 'Custom Left', - onLeftButtonPress: () => this.props.navigator.pop(), - rightButtonIcon: nativeImageSource({ - ios: 'NavBarButtonPlus', - width: 17, - height: 17 - }), - onRightButtonPress: () => { - AlertIOS.alert( - 'Bar Button Action', - 'Recognized a tap on the bar button icon', - [ - { - text: 'OK', - onPress: () => console.log('Tapped OK'), - }, - ] - ); - }, - passProps: { - text: 'This page has an icon for the right button in the nav bar', - } - }); - })} - {this._renderRow('Custom Left & Right System Icons', () => { - this.props.navigator.push({ - title: NavigatorIOSExample.title, - component: EmptyPage, - leftButtonSystemIcon: 'cancel', - onLeftButtonPress: () => this.props.navigator.pop(), - rightButtonSystemIcon: 'search', - onRightButtonPress: () => { - AlertIOS.alert( - 'Bar Button Action', - 'Recognized a tap on the bar button icon', - [ - { - text: 'OK', - onPress: () => console.log('Tapped OK'), - }, - ] - ); - }, - passProps: { - text: 'This page has an icon for the right button in the nav bar', - } - }); - })} - {this._renderRow('Pop', () => { - this.props.navigator.pop(); - })} - {this._renderRow('Pop to top', () => { - this.props.navigator.popToTop(); - })} - {this._renderReplace()} - {this._renderReplacePrevious()} - {this._renderReplacePreviousAndPop()} - {this._renderRow('Exit NavigatorIOS Example', this.props.onExampleExit)} - </View> - <View style={styles.line}/> - </ScrollView> - ); - } - - _renderReplace = () => { - if (!this.props.depth) { - // this is to avoid replacing the top of the stack - return null; - } - return this._renderRow('Replace here', () => { - var prevRoute = this.props.route; - this.props.navigator.replace({ - title: 'New Navigation', - component: EmptyPage, - rightButtonTitle: 'Undo', - onRightButtonPress: () => this.props.navigator.replace(prevRoute), - passProps: { - text: 'The component is replaced, but there is currently no ' + - 'way to change the right button or title of the current route', - } - }); - }); - }; - - _renderReplacePrevious = () => { - if (!this.props.depth || this.props.depth < 2) { - // this is to avoid replacing the top of the stack - return null; - } - return this._renderRow('Replace previous', () => { - this.props.navigator.replacePrevious({ - title: 'Replaced', - component: EmptyPage, - passProps: { - text: 'This is a replaced "previous" page', - }, - wrapperStyle: styles.customWrapperStyle, - }); - }); - }; - - _renderReplacePreviousAndPop = () => { - if (!this.props.depth || this.props.depth < 2) { - // this is to avoid replacing the top of the stack - return null; - } - return this._renderRow('Replace previous and pop', () => { - this.props.navigator.replacePreviousAndPop({ - title: 'Replaced and Popped', - component: EmptyPage, - passProps: { - text: 'This is a replaced "previous" page', - }, - wrapperStyle: styles.customWrapperStyle, - }); - }); - }; - - _renderRow = (title: string, onPress: Function) => { - return ( - <View> - <TouchableHighlight onPress={onPress}> - <View style={styles.row}> - <Text style={styles.rowText}> - {title} - </Text> - </View> - </TouchableHighlight> - <View style={styles.separator} /> - </View> - ); - }; -} - -class NavigatorIOSExample extends React.Component { - static title = '<NavigatorIOS>'; - static description = 'iOS navigation capabilities'; - static external = true; - - render() { - const {onExampleExit} = this.props; - return ( - <NavigatorIOS - style={styles.container} - initialRoute={{ - title: NavigatorIOSExample.title, - component: NavigatorIOSExamplePage, - passProps: {onExampleExit}, - }} - tintColor="#008888" - /> - ); - } -} - -const styles = StyleSheet.create({ - container: { - flex: 1, - }, - customWrapperStyle: { - backgroundColor: '#bbdddd', - }, - emptyPage: { - flex: 1, - paddingTop: 64, - }, - emptyPageText: { - margin: 10, - }, - list: { - backgroundColor: '#eeeeee', - marginTop: 10, - }, - group: { - backgroundColor: 'white', - }, - groupSpace: { - height: 15, - }, - line: { - backgroundColor: '#bbbbbb', - height: StyleSheet.hairlineWidth, - }, - row: { - backgroundColor: 'white', - justifyContent: 'center', - paddingHorizontal: 15, - paddingVertical: 15, - }, - separator: { - height: StyleSheet.hairlineWidth, - backgroundColor: '#bbbbbb', - marginLeft: 15, - }, - rowNote: { - fontSize: 17, - }, - rowText: { - fontSize: 17, - fontWeight: '500', - }, -}); - -module.exports = NavigatorIOSExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/netinfo.html b/docs/netinfo.html index 7c6e94a66b1..3916d9bea66 100644 --- a/docs/netinfo.html +++ b/docs/netinfo.html @@ -1,4 +1,4 @@ -NetInfo

    NetInfo #

    NetInfo exposes info about online/offline status

    NetInfo.fetch().done((reach) => { +NetInfo

    NetInfo #

    NetInfo exposes info about online/offline status

    NetInfo.fetch().then((reach) => { console.log('Initial: ' + reach); }); function handleFirstConnectivityChange(reach) { @@ -40,180 +40,7 @@ The listener receives one of the connectivity types listed above.

    static isConnectionExpensive() #

    Properties #

    isConnected: ObjectExpression #

    An object with the same methods as above but the listener receives a boolean which represents the internet connectivity. Use this if you are only interested with whether the device has internet -connectivity.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -const React = require('react'); -const ReactNative = require('react-native'); -const { - NetInfo, - Text, - View, - TouchableWithoutFeedback, -} = ReactNative; - -class ConnectionInfoSubscription extends React.Component { - state = { - connectionInfoHistory: [], - }; - - componentDidMount() { - NetInfo.addEventListener( - 'change', - this._handleConnectionInfoChange - ); - } - - componentWillUnmount() { - NetInfo.removeEventListener( - 'change', - this._handleConnectionInfoChange - ); - } - - _handleConnectionInfoChange = (connectionInfo) => { - const connectionInfoHistory = this.state.connectionInfoHistory.slice(); - connectionInfoHistory.push(connectionInfo); - this.setState({ - connectionInfoHistory, - }); - }; - - render() { - return ( - <View> - <Text>{JSON.stringify(this.state.connectionInfoHistory)}</Text> - </View> - ); - } -} - -class ConnectionInfoCurrent extends React.Component { - state = { - connectionInfo: null, - }; - - componentDidMount() { - NetInfo.addEventListener( - 'change', - this._handleConnectionInfoChange - ); - NetInfo.fetch().done( - (connectionInfo) => { this.setState({connectionInfo}); } - ); - } - - componentWillUnmount() { - NetInfo.removeEventListener( - 'change', - this._handleConnectionInfoChange - ); - } - - _handleConnectionInfoChange = (connectionInfo) => { - this.setState({ - connectionInfo, - }); - }; - - render() { - return ( - <View> - <Text>{this.state.connectionInfo}</Text> - </View> - ); - } -} - -class IsConnected extends React.Component { - state = { - isConnected: null, - }; - - componentDidMount() { - NetInfo.isConnected.addEventListener( - 'change', - this._handleConnectivityChange - ); - NetInfo.isConnected.fetch().done( - (isConnected) => { this.setState({isConnected}); } - ); - } - - componentWillUnmount() { - NetInfo.isConnected.removeEventListener( - 'change', - this._handleConnectivityChange - ); - } - - _handleConnectivityChange = (isConnected) => { - this.setState({ - isConnected, - }); - }; - - render() { - return ( - <View> - <Text>{this.state.isConnected ? 'Online' : 'Offline'}</Text> - </View> - ); - } -} - -class IsConnectionExpensive extends React.Component { - state = { - isConnectionExpensive: (null : ?boolean), - }; - - _checkIfExpensive = () => { - NetInfo.isConnectionExpensive().then( - isConnectionExpensive => { this.setState({isConnectionExpensive}); } - ); - }; - - render() { - return ( - <View> - <TouchableWithoutFeedback onPress={this._checkIfExpensive}> - <View> - <Text>Click to see if connection is expensive: - {this.state.isConnectionExpensive === true ? 'Expensive' : - this.state.isConnectionExpensive === false ? 'Not expensive' - : 'Unknown'} - </Text> - </View> - </TouchableWithoutFeedback> - </View> - ); - } -} - -exports.title = 'NetInfo'; -exports.description = 'Monitor network status'; -exports.examples = [ - { - title: 'NetInfo.isConnected', - description: 'Asynchronously load and observe connectivity', - render(): React.Element<any> { return <IsConnected />; } - }, - { - title: 'NetInfo.update', - description: 'Asynchronously load and observe connectionInfo', - render(): React.Element<any> { return <ConnectionInfoCurrent />; } - }, - { - title: 'NetInfo.updateHistory', - description: 'Observed updates to connectionInfo', - render(): React.Element<any> { return <ConnectionInfoSubscription />; } - }, - { - platform: 'android', - title: 'NetInfo.isConnectionExpensive (Android)', - description: 'Asynchronously check isConnectionExpensive', - render(): React.Element<any> { return <IsConnectionExpensive />; } - }, -];
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/network.html b/docs/network.html index b80c5802bc8..f0123ef5a68 100644 --- a/docs/network.html +++ b/docs/network.html @@ -1,4 +1,4 @@ -Networking

    Networking #

    Many mobile apps need to load resources from a remote URL. You may want to make a POST request to a REST API, or you may simply need to fetch a chunk of static content from another server.

    Using Fetch #

    React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.

    Making requests #

    In order to fetch content from an arbitrary URL, just pass the URL to fetch:

    fetch('https://mywebsite.com/mydata.json')

    Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:

    fetch('https://mywebsite.com/endpoint/', { +Networking

    Networking #

    Many mobile apps need to load resources from a remote URL. You may want to make a POST request to a REST API, or you may simply need to fetch a chunk of static content from another server.

    Using Fetch #

    React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.

    Making requests #

    In order to fetch content from an arbitrary URL, just pass the URL to fetch:

    fetch('https://mywebsite.com/mydata.json')

    Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:

    fetch('https://mywebsite.com/endpoint/', { method: 'POST', headers: { 'Accept': 'application/json', @@ -25,7 +25,53 @@ } catch(error) { console.error(error); } - }

    Don't forget to catch any errors that may be thrown by fetch, otherwise they will be dropped silently.

    By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception. If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely. Note however that from January 2017, Apple's App Store review will require reasonable justification for disabling ATS. See Apple's documentation for more information.

    Using Other Networking Libraries #

    The XMLHttpRequest API is built in to React Native. This means that you can use third party libraries such as frisbee or axios that depend on it, or you can use the XMLHttpRequest API directly if you prefer.

    var request = new XMLHttpRequest(); + }

    Don't forget to catch any errors that may be thrown by fetch, otherwise they will be dropped silently.

    By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception. If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely. Note however that from January 2017, Apple's App Store review will require reasonable justification for disabling ATS. See Apple's documentation for more information.

    Using Other Networking Libraries #

    The XMLHttpRequest API is built in to React Native. This means that you can use third party libraries such as frisbee or axios that depend on it, or you can use the XMLHttpRequest API directly if you prefer.

    var request = new XMLHttpRequest(); request.onreadystatechange = (e) => { if (request.readyState !== 4) { return; @@ -60,7 +106,7 @@ ws.onerror = ws.onclose = (e) => { // connection closed console.log(e.code, e.reason); -};

    Your app can now display all sorts of data and you may soon need to organize this content into several screens. To manage the transition between these screens, you will need to learn about navigators.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/panresponder.html b/docs/panresponder.html index 4c3b9a9769e..8a04982cfa3 100644 --- a/docs/panresponder.html +++ b/docs/panresponder.html @@ -1,4 +1,4 @@ -PanResponder

    PanResponder #

    PanResponder reconciles several touches into a single gesture. It makes +PanResponder

    PanResponder #

    PanResponder reconciles several touches into a single gesture. It makes single-touch gestures resilient to extra touches, and can be used to recognize simple multi-touch gestures.

    By default, PanResponder holds an InteractionManager handle to block long-running JS events from interrupting active gestures.

    It provides a predictable wrapper of the responder handlers provided by the @@ -14,7 +14,7 @@ native event object:

    onPanResponderMov onMoveShouldSetPanResponderCapture: (evt, gestureState) => true, onPanResponderGrant: (evt, gestureState) => { - // The guesture has started. Show visual feedback so the user knows + // The gesture has started. Show visual feedback so the user knows // what is happening! // gestureState.d{x,y} will be set to zero now @@ -47,7 +47,7 @@ native event object:

    onPanResponderMov <View {...this._panResponder.panHandlers} /> ); },

    Working Example #

    To see it in action, try the -PanResponder example in UIExplorer

    Methods #

    static create(config) #

    @param {object} config Enhanced versions of all of the responder callbacks +PanResponder example in RNTester

    Methods #

    static create(config) #

    @param {object} config Enhanced versions of all of the responder callbacks that provide not only the typical ResponderSyntheticEvent, but also the PanResponder gesture state. Simply replace the word Responder with PanResponder in each of the typical onResponder* callbacks. For @@ -58,125 +58,7 @@ as well.

    Be careful with onStartShould* callbacks. They only reflect updat Once the node is the responder, you can rely on every start/end event being processed by the gesture and gestureState being updated accordingly. (numberActiveTouches) may not be totally accurate unless you -are the responder.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - PanResponder, - StyleSheet, - View, -} = ReactNative; - -var CIRCLE_SIZE = 80; - -var PanResponderExample = React.createClass({ - - statics: { - title: 'PanResponder Sample', - description: 'Shows the use of PanResponder to provide basic gesture handling.', - }, - - _panResponder: {}, - _previousLeft: 0, - _previousTop: 0, - _circleStyles: {}, - circle: (null : ?{ setNativeProps(props: Object): void }), - - componentWillMount: function() { - this._panResponder = PanResponder.create({ - onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder, - onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder, - onPanResponderGrant: this._handlePanResponderGrant, - onPanResponderMove: this._handlePanResponderMove, - onPanResponderRelease: this._handlePanResponderEnd, - onPanResponderTerminate: this._handlePanResponderEnd, - }); - this._previousLeft = 20; - this._previousTop = 84; - this._circleStyles = { - style: { - left: this._previousLeft, - top: this._previousTop, - backgroundColor: 'green', - } - }; - }, - - componentDidMount: function() { - this._updateNativeStyles(); - }, - - render: function() { - return ( - <View - style={styles.container}> - <View - ref={(circle) => { - this.circle = circle; - }} - style={styles.circle} - {...this._panResponder.panHandlers} - /> - </View> - ); - }, - - _highlight: function() { - this._circleStyles.style.backgroundColor = 'blue'; - this._updateNativeStyles(); - }, - - _unHighlight: function() { - this._circleStyles.style.backgroundColor = 'green'; - this._updateNativeStyles(); - }, - - _updateNativeStyles: function() { - this.circle && this.circle.setNativeProps(this._circleStyles); - }, - - _handleStartShouldSetPanResponder: function(e: Object, gestureState: Object): boolean { - // Should we become active when the user presses down on the circle? - return true; - }, - - _handleMoveShouldSetPanResponder: function(e: Object, gestureState: Object): boolean { - // Should we become active when the user moves a touch over the circle? - return true; - }, - - _handlePanResponderGrant: function(e: Object, gestureState: Object) { - this._highlight(); - }, - _handlePanResponderMove: function(e: Object, gestureState: Object) { - this._circleStyles.style.left = this._previousLeft + gestureState.dx; - this._circleStyles.style.top = this._previousTop + gestureState.dy; - this._updateNativeStyles(); - }, - _handlePanResponderEnd: function(e: Object, gestureState: Object) { - this._unHighlight(); - this._previousLeft += gestureState.dx; - this._previousTop += gestureState.dy; - }, -}); - -var styles = StyleSheet.create({ - circle: { - width: CIRCLE_SIZE, - height: CIRCLE_SIZE, - borderRadius: CIRCLE_SIZE / 2, - position: 'absolute', - left: 0, - top: 0, - }, - container: { - flex: 1, - paddingTop: 64, - }, -}); - -module.exports = PanResponderExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/performance.html b/docs/performance.html index 37a28ed9593..8763cdc9923 100644 --- a/docs/performance.html +++ b/docs/performance.html @@ -1,4 +1,4 @@ -Performance

    Performance #

    A compelling reason for using React Native instead of WebView-based tools is to achieve 60 frames per second and a native look and feel to your apps. +Performance

    Performance #

    A compelling reason for using React Native instead of WebView-based tools is to achieve 60 frames per second and a native look and feel to your apps. Where possible, we would like for React Native to do the right thing and help you to focus on your app instead of performance optimization, but there are areas where we're not quite there yet, and others where React Native (similar to writing native code directly) cannot possibly determine the best way to optimize for you and so manual intervention will be necessary. @@ -28,7 +28,14 @@ and so they are not interrupted by frame drops on the JavaScript thread.

    S The scroll events are dispatched to the JS thread, but their receipt is not necessary for the scroll to occur.

    Common sources of performance problems #

    Running in development mode (dev=true) #

    JavaScript thread performance suffers greatly when running in dev mode. This is unavoidable: a lot more work needs to be done at runtime to provide you with good warnings and error messages, such as validating propTypes and various other assertions. Always make sure to test performance in release builds.

    Using console.log statements #

    When running a bundled app, these statements can cause a big bottleneck in the JavaScript thread. This includes calls from debugging libraries such as redux-logger, -so make sure to remove them before bundling.

    ListView initial rendering is too slow or scroll performance is bad for large lists #

    Use the new FlatList or SectionList component instead. +so make sure to remove them before bundling. +You can also use this babel plugin that removes all the console.* calls. You need to install it first with npm i babel-plugin-transform-remove-console --save, and then edit the .babelrc file under your project directory like this:

    { + "env": { + "production": { + "plugins": ["transform-remove-console"] + } + } +}

    This will automatically remove all console.* calls in the release (production) versions of your project.

    ListView initial rendering is too slow or scroll performance is bad for large lists #

    Use the new FlatList or SectionList component instead. Besides simplifying the API, the new list components also have significant performance enhancements, the main one being nearly constant memory usage for any number of rows.

    JS FPS plunges when re-rendering a view that hardly changes #

    If you are using a ListView, you must provide a rowHasChanged function that can reduce a lot of work by quickly determining whether or not a row needs to be re-rendered. If you are using immutable data structures, this would be as simple as a reference equality check.

    Similarly, you can implement shouldComponentUpdate and indicate the exact conditions under which you would like the component to re-render. If you write pure components (where the return value of the render function is entirely dependent on props and state), you can leverage PureRenderMixin to do this for you. Once again, immutable data structures are useful to keep this fast -- if you have to do a deep comparison of a large list of objects, it may be that re-rendering your entire component would be quicker, and it would certainly require less code.

    Dropping JS thread FPS because of doing a lot of work on the JavaScript thread at the same time #

    "Slow Navigator transitions" is the most common manifestation of this, but there are other times this can happen. Using InteractionManager can be a good approach, but if the user experience cost is too high to delay work during an animation, then you might want to consider LayoutAnimation.

    The Animated api currently calculates each keyframe on-demand on the JavaScript thread, while LayoutAnimation leverages Core Animation and is unaffected by JS thread and main thread frame drops.

    One case where I have used this is for animating in a modal (sliding down from top and fading in a translucent overlay) while initializing and perhaps receiving responses for several network requests, rendering the contents of the modal, and updating the view where the modal was opened from. See the Animations guide for more information about how to use LayoutAnimation.

    Caveats:

    • LayoutAnimation only works for fire-and-forget animations ("static" animations) -- if it must be be interruptible, you will need to use Animated.

    Moving a view on the screen (scrolling, translating, rotating) drops UI thread FPS #

    This is especially true when you have text with a transparent background positioned on top of an image, or any other situation where alpha compositing would be required to re-draw the view on each frame. @@ -114,6 +121,6 @@ And many times, you'll want to look into \ No newline at end of file + \ No newline at end of file diff --git a/docs/permissionsandroid.html b/docs/permissionsandroid.html index 7aea52ddf75..ec6020d61c2 100644 --- a/docs/permissionsandroid.html +++ b/docs/permissionsandroid.html @@ -1,4 +1,15 @@ -PermissionsAndroid

    PermissionsAndroid #

    PermissionsAndroid provides access to Android M's new permissions model. +PermissionsAndroid

    PermissionsAndroid #

    + +

    PermissionsAndroid provides access to Android M's new permissions model. Some permissions are granted by default when the application is installed so long as they appear in AndroidManifest.xml. However, "dangerous" permissions require a dialog prompt. You should use this module for those @@ -55,6 +66,6 @@ indicating whether the user allowed or denied the request

    < apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/picker.html b/docs/picker.html index 1e016d1184f..90f40ebbd7d 100644 --- a/docs/picker.html +++ b/docs/picker.html @@ -1,130 +1,12 @@ -Picker

    Picker #

    Renders the native picker component on iOS and Android. Example:

    <Picker +Picker

    Picker #

    Renders the native picker component on iOS and Android. Example:

    <Picker selectedValue={this.state.language} - onValueChange={(lang) => this.setState({language: lang})}> + onValueChange={(itemValue, itemIndex) => this.setState({language: itemValue})}> <Picker.Item label="Java" value="java" /> <Picker.Item label="JavaScript" value="js" /> </Picker>

    Props #

    onValueChange?: Function #

    Callback for when an item is selected. This is called with the following parameters: - itemValue: the value prop of the item that was selected - itemPosition: the index of the selected item in this picker

    selectedValue?: any #

    Value matching value of one of the items. Can be a string or an integer.

    style?: $FlowFixMe #

    testID?: string #

    Used to locate this view in end-to-end tests.

    androidenabled?: boolean #

    If set to false, the picker will be disabled, i.e. the user will not be able to make a -selection.

    androidmode?: literal | literal #

    On Android, specifies how to display the selection items when the user taps on the picker:

    • 'dialog': Show a modal dialog. This is the default.
    • 'dropdown': Shows a dropdown anchored to the picker view

    androidprompt?: string #

    Prompt string for this picker, used on Android in dialog mode as the title of the dialog.

    iositemStyle?: $FlowFixMe #

    Style to apply to each of the item labels.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -const React = require('react'); -const ReactNative = require('react-native'); -const StyleSheet = require('StyleSheet'); -const UIExplorerBlock = require('UIExplorerBlock'); -const UIExplorerPage = require('UIExplorerPage'); - -const { - Picker, - Text, -} = ReactNative; - -const Item = Picker.Item; - -class PickerExample extends React.Component { - static title = '<Picker>'; - static description = 'Provides multiple options to choose from, using either a dropdown menu or a dialog.'; - - state = { - selected1: 'key1', - selected2: 'key1', - selected3: 'key1', - color: 'red', - mode: Picker.MODE_DIALOG, - }; - - render() { - return ( - <UIExplorerPage title="<Picker>"> - <UIExplorerBlock title="Basic Picker"> - <Picker - style={styles.picker} - selectedValue={this.state.selected1} - onValueChange={this.onValueChange.bind(this, 'selected1')}> - <Item label="hello" value="key0" /> - <Item label="world" value="key1" /> - </Picker> - </UIExplorerBlock> - <UIExplorerBlock title="Disabled picker"> - <Picker style={styles.picker} enabled={false} selectedValue={this.state.selected1}> - <Item label="hello" value="key0" /> - <Item label="world" value="key1" /> - </Picker> - </UIExplorerBlock> - <UIExplorerBlock title="Dropdown Picker"> - <Picker - style={styles.picker} - selectedValue={this.state.selected2} - onValueChange={this.onValueChange.bind(this, 'selected2')} - mode="dropdown"> - <Item label="hello" value="key0" /> - <Item label="world" value="key1" /> - </Picker> - </UIExplorerBlock> - <UIExplorerBlock title="Picker with prompt message"> - <Picker - style={styles.picker} - selectedValue={this.state.selected3} - onValueChange={this.onValueChange.bind(this, 'selected3')} - prompt="Pick one, just one"> - <Item label="hello" value="key0" /> - <Item label="world" value="key1" /> - </Picker> - </UIExplorerBlock> - <UIExplorerBlock title="Picker with no listener"> - <Picker style={styles.picker}> - <Item label="hello" value="key0" /> - <Item label="world" value="key1" /> - </Picker> - <Text> - Cannot change the value of this picker because it doesn't update selectedValue. - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Colorful pickers"> - <Picker - style={[styles.picker, {color: 'white', backgroundColor: '#333'}]} - selectedValue={this.state.color} - onValueChange={this.onValueChange.bind(this, 'color')} - mode="dropdown"> - <Item label="red" color="red" value="red" /> - <Item label="green" color="green" value="green" /> - <Item label="blue" color="blue" value="blue" /> - </Picker> - <Picker - style={styles.picker} - selectedValue={this.state.color} - onValueChange={this.onValueChange.bind(this, 'color')} - mode="dialog"> - <Item label="red" color="red" value="red" /> - <Item label="green" color="green" value="green" /> - <Item label="blue" color="blue" value="blue" /> - </Picker> - </UIExplorerBlock> - </UIExplorerPage> - ); - } - - changeMode = () => { - const newMode = this.state.mode === Picker.MODE_DIALOG - ? Picker.MODE_DROPDOWN - : Picker.MODE_DIALOG; - this.setState({mode: newMode}); - }; - - onValueChange = (key: string, value: string) => { - const newState = {}; - newState[key] = value; - this.setState(newState); - }; -} - -var styles = StyleSheet.create({ - picker: { - width: 100, - }, -}); - -module.exports = PickerExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/pickerios.html b/docs/pickerios.html index 33deb88ef17..54f8b799af1 100644 --- a/docs/pickerios.html +++ b/docs/pickerios.html @@ -1,138 +1,4 @@ -PickerIOS

    PickerIOS #

    Props #

    itemStyle?: itemStylePropType #

    onValueChange?: function #

    selectedValue?: any #

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - PickerIOS, - Text, - View, -} = ReactNative; - -var PickerItemIOS = PickerIOS.Item; - -var CAR_MAKES_AND_MODELS = { - amc: { - name: 'AMC', - models: ['AMX', 'Concord', 'Eagle', 'Gremlin', 'Matador', 'Pacer'], - }, - alfa: { - name: 'Alfa-Romeo', - models: ['159', '4C', 'Alfasud', 'Brera', 'GTV6', 'Giulia', 'MiTo', 'Spider'], - }, - aston: { - name: 'Aston Martin', - models: ['DB5', 'DB9', 'DBS', 'Rapide', 'Vanquish', 'Vantage'], - }, - audi: { - name: 'Audi', - models: ['90', '4000', '5000', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'Q5', 'Q7'], - }, - austin: { - name: 'Austin', - models: ['America', 'Maestro', 'Maxi', 'Mini', 'Montego', 'Princess'], - }, - borgward: { - name: 'Borgward', - models: ['Hansa', 'Isabella', 'P100'], - }, - buick: { - name: 'Buick', - models: ['Electra', 'LaCrosse', 'LeSabre', 'Park Avenue', 'Regal', - 'Roadmaster', 'Skylark'], - }, - cadillac: { - name: 'Cadillac', - models: ['Catera', 'Cimarron', 'Eldorado', 'Fleetwood', 'Sedan de Ville'], - }, - chevrolet: { - name: 'Chevrolet', - models: ['Astro', 'Aveo', 'Bel Air', 'Captiva', 'Cavalier', 'Chevelle', - 'Corvair', 'Corvette', 'Cruze', 'Nova', 'SS', 'Vega', 'Volt'], - }, -}; - -class PickerExample extends React.Component { - state = { - carMake: 'cadillac', - modelIndex: 3, - }; - - render() { - var make = CAR_MAKES_AND_MODELS[this.state.carMake]; - var selectionString = make.name + ' ' + make.models[this.state.modelIndex]; - return ( - <View> - <Text>Please choose a make for your car:</Text> - <PickerIOS - selectedValue={this.state.carMake} - onValueChange={(carMake) => this.setState({carMake, modelIndex: 0})}> - {Object.keys(CAR_MAKES_AND_MODELS).map((carMake) => ( - <PickerItemIOS - key={carMake} - value={carMake} - label={CAR_MAKES_AND_MODELS[carMake].name} - /> - ))} - </PickerIOS> - <Text>Please choose a model of {make.name}:</Text> - <PickerIOS - selectedValue={this.state.modelIndex} - key={this.state.carMake} - onValueChange={(modelIndex) => this.setState({modelIndex})}> - {CAR_MAKES_AND_MODELS[this.state.carMake].models.map((modelName, modelIndex) => ( - <PickerItemIOS - key={this.state.carMake + '_' + modelIndex} - value={modelIndex} - label={modelName} - /> - ))} - </PickerIOS> - <Text>You selected: {selectionString}</Text> - </View> - ); - } -} - -class PickerStyleExample extends React.Component { - state = { - carMake: 'cadillac', - modelIndex: 0, - }; - - render() { - return ( - <PickerIOS - itemStyle={{fontSize: 25, color: 'red', textAlign: 'left', fontWeight: 'bold'}} - selectedValue={this.state.carMake} - onValueChange={(carMake) => this.setState({carMake, modelIndex: 0})}> - {Object.keys(CAR_MAKES_AND_MODELS).map((carMake) => ( - <PickerItemIOS - key={carMake} - value={carMake} - label={CAR_MAKES_AND_MODELS[carMake].name} - /> - ))} - </PickerIOS> - ); - } -} - -exports.displayName = (undefined: ?string); -exports.title = '<PickerIOS>'; -exports.description = 'Render lists of selectable options with UIPickerView.'; -exports.examples = [ -{ - title: '<PickerIOS>', - render: function(): React.Element<any> { - return <PickerExample />; - }, -}, -{ - title: '<PickerIOS> with custom styling', - render: function(): React.Element<any> { - return <PickerStyleExample />; - }, -}];

    PickerIOS #

    Props #

    itemStyle?: itemStylePropType #

    onValueChange?: PropTypes.func #

    selectedValue?: PropTypes.any #

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/pixelratio.html b/docs/pixelratio.html index 3d0703fbea8..fff2588fc12 100644 --- a/docs/pixelratio.html +++ b/docs/pixelratio.html @@ -1,4 +1,4 @@ -PixelRatio

    PixelRatio #

    PixelRatio class gives access to the device pixel density.

    Fetching a correctly sized image #

    You should get a higher resolution image if you are on a high pixel density +PixelRatio

    PixelRatio #

    PixelRatio class gives access to the device pixel density.

    Fetching a correctly sized image #

    You should get a higher resolution image if you are on a high pixel density device. A good rule of thumb is to multiply the size of the image you display by the pixel ratio.

    var image = getImage({ width: PixelRatio.getPixelSizeForLayoutSize(200), @@ -27,6 +27,6 @@ exactly (8.33 * 3) = 25 pixels.

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/platform-specific-code.html b/docs/platform-specific-code.html index bd6f84dcd3b..c79b0e88af1 100644 --- a/docs/platform-specific-code.html +++ b/docs/platform-specific-code.html @@ -1,4 +1,4 @@ -Platform Specific Code

    Platform Specific Code #

    When building a cross-platform app, you'll want to re-use as much code as possible. Scenarios may arise where it makes sense for the code to be different, for example you may want to implement separate visual components for iOS and Android.

    React Native provides two ways to easily organize your code and separate it by platform:

    Certain components may have properties that work on one platform only. All of these props are annotated with @platform and have a small badge next to them on the website.

    Platform module #

    React Native provides a module that detects the platform in which the app is running. You can use the detection logic to implement platform-specific code. Use this option when only small parts of a component are platform-specific.

    import { Platform, StyleSheet } from 'react-native'; +Platform Specific Code

    Platform Specific Code #

    When building a cross-platform app, you'll want to re-use as much code as possible. Scenarios may arise where it makes sense for the code to be different, for example you may want to implement separate visual components for iOS and Android.

    React Native provides two ways to easily organize your code and separate it by platform:

    Certain components may have properties that work on one platform only. All of these props are annotated with @platform and have a small badge next to them on the website.

    Platform module #

    React Native provides a module that detects the platform in which the app is running. You can use the detection logic to implement platform-specific code. Use this option when only small parts of a component are platform-specific.

    import { Platform, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ height: (Platform.OS === 'ios') ? 200 : 100, @@ -42,6 +42,6 @@ BigButton.android \ No newline at end of file + \ No newline at end of file diff --git a/docs/progressbarandroid.html b/docs/progressbarandroid.html index b11bcba9c27..dca56ebf257 100644 --- a/docs/progressbarandroid.html +++ b/docs/progressbarandroid.html @@ -1,4 +1,4 @@ -ProgressBarAndroid

    ProgressBarAndroid #

    React component that wraps the Android-only ProgressBar. This component is used to indicate +ProgressBarAndroid

    ProgressBarAndroid #

    React component that wraps the Android-only ProgressBar. This component is used to indicate that the app is loading or there is some activity in the app.

    Example:

    render: function() { var progressBar = <View style={styles.container}> @@ -13,66 +13,7 @@ that the app is loading or there is some activity in the app.

    Example:

    /> ); },

    Props #

    color?: color #

    Color of the progress bar.

    indeterminate?: indeterminateType #

    If the progress bar will show indeterminate progress. Note that this -can only be false if styleAttr is Horizontal.

    progress?: number #

    The progress value (between 0 and 1).

    styleAttr?: enum('Horizontal', 'Normal', 'Small', 'Large', 'Inverse', 'SmallInverse', 'LargeInverse') #

    Style of the ProgressBar. One of:

    • Horizontal
    • Normal (default)
    • Small
    • Large
    • Inverse
    • SmallInverse
    • LargeInverse

    testID?: string #

    Used to locate this view in end-to-end tests.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var ProgressBar = require('ProgressBarAndroid'); -var React = require('React'); -var UIExplorerBlock = require('UIExplorerBlock'); -var UIExplorerPage = require('UIExplorerPage'); - -var TimerMixin = require('react-timer-mixin'); - -var MovingBar = React.createClass({ - mixins: [TimerMixin], - - getInitialState: function() { - return { - progress: 0 - }; - }, - - componentDidMount: function() { - this.setInterval( - () => { - var progress = (this.state.progress + 0.02) % 1; - this.setState({progress: progress}); - }, 50 - ); - }, - - render: function() { - return <ProgressBar progress={this.state.progress} {...this.props} />; - }, -}); - -class ProgressBarAndroidExample extends React.Component { - static title = '<ProgressBarAndroid>'; - static description = 'Horizontal bar to show the progress of some operation.'; - - render() { - return ( - <UIExplorerPage title="ProgressBar Examples"> - <UIExplorerBlock title="Horizontal Indeterminate ProgressBar"> - <ProgressBar styleAttr="Horizontal" /> - </UIExplorerBlock> - - <UIExplorerBlock title="Horizontal ProgressBar"> - <MovingBar styleAttr="Horizontal" indeterminate={false} /> - </UIExplorerBlock> - - <UIExplorerBlock title="Horizontal Black Indeterminate ProgressBar"> - <ProgressBar styleAttr="Horizontal" color="black" /> - </UIExplorerBlock> - - <UIExplorerBlock title="Horizontal Blue ProgressBar"> - <MovingBar styleAttr="Horizontal" indeterminate={false} color="blue" /> - </UIExplorerBlock> - </UIExplorerPage> - ); - } -} - -module.exports = ProgressBarAndroidExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/progressviewios.html b/docs/progressviewios.html index 5f563e0b538..fdde034c74a 100644 --- a/docs/progressviewios.html +++ b/docs/progressviewios.html @@ -1,73 +1,4 @@ -ProgressViewIOS

    ProgressViewIOS #

    Use ProgressViewIOS to render a UIProgressView on iOS.

    Props #

    progress?: number #

    The progress value (between 0 and 1).

    progressImage?: Image.propTypes.source #

    A stretchable image to display as the progress bar.

    progressTintColor?: string #

    The tint color of the progress bar itself.

    progressViewStyle?: enum('default', 'bar') #

    The progress bar style.

    trackImage?: Image.propTypes.source #

    A stretchable image to display behind the progress bar.

    trackTintColor?: string #

    The tint color of the progress bar track.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - ProgressViewIOS, - StyleSheet, - View, -} = ReactNative; -var TimerMixin = require('react-timer-mixin'); - -var ProgressViewExample = React.createClass({ - mixins: [TimerMixin], - - getInitialState() { - return { - progress: 0, - }; - }, - - componentDidMount() { - this.updateProgress(); - }, - - updateProgress() { - var progress = this.state.progress + 0.01; - this.setState({ progress }); - this.requestAnimationFrame(() => this.updateProgress()); - }, - - getProgress(offset) { - var progress = this.state.progress + offset; - return Math.sin(progress % Math.PI) % 1; - }, - - render() { - return ( - <View style={styles.container}> - <ProgressViewIOS style={styles.progressView} progress={this.getProgress(0)}/> - <ProgressViewIOS style={styles.progressView} progressTintColor="purple" progress={this.getProgress(0.2)}/> - <ProgressViewIOS style={styles.progressView} progressTintColor="red" progress={this.getProgress(0.4)}/> - <ProgressViewIOS style={styles.progressView} progressTintColor="orange" progress={this.getProgress(0.6)}/> - <ProgressViewIOS style={styles.progressView} progressTintColor="yellow" progress={this.getProgress(0.8)}/> - </View> - ); - }, -}); - -exports.displayName = (undefined: ?string); -exports.framework = 'React'; -exports.title = 'ProgressViewIOS'; -exports.description = 'ProgressViewIOS'; -exports.examples = [{ - title: 'ProgressViewIOS', - render() { - return ( - <ProgressViewExample/> - ); - } -}]; - -var styles = StyleSheet.create({ - container: { - marginTop: -20, - backgroundColor: 'transparent', - }, - progressView: { - marginTop: 20, - } -});

    ProgressViewIOS #

    Use ProgressViewIOS to render a UIProgressView on iOS.

    Props #

    progress?: PropTypes.number #

    The progress value (between 0 and 1).

    progressImage?: Image.propTypes.source #

    A stretchable image to display as the progress bar.

    progressTintColor?: PropTypes.string #

    The tint color of the progress bar itself.

    progressViewStyle?: PropTypes.oneOf(['default', 'bar']) #

    The progress bar style.

    trackImage?: Image.propTypes.source #

    A stretchable image to display behind the progress bar.

    trackTintColor?: PropTypes.string #

    The tint color of the progress bar track.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/props.html b/docs/props.html index 97f271291e6..0f0180ab4d0 100644 --- a/docs/props.html +++ b/docs/props.html @@ -1,8 +1,8 @@ -Props

    Props #

    Most components can be customized when they are created, with different parameters. These creation parameters are called props.

    For example, one basic React Native component is the Image. When you +Props

    Props #

    Most components can be customized when they are created, with different parameters. These creation parameters are called props.

    For example, one basic React Native component is the Image. When you create an image, you can use a prop named source to control what image it shows.

    import React, { Component } from 'react'; import { AppRegistry, Image } from 'react-native'; -class Bananas extends Component { +export default class Bananas extends Component { render() { let pic = { uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg' @@ -12,8 +12,9 @@ class Bananas extends ); } } - -AppRegistry.registerComponent('Bananas', () => Bananas);

    Notice that {pic} is surrounded by braces, to embed the variable pic into JSX. You can put any JavaScript expression inside braces in JSX.

    Your own components can also use props. This lets you make a single component + +// skip this line if using Create React Native App +AppRegistry.registerComponent('Bananas', () => Bananas);

    Notice that {pic} is surrounded by braces, to embed the variable pic into JSX. You can put any JavaScript expression inside braces in JSX.

    Your own components can also use props. This lets you make a single component that is used in many different places in your app, with slightly different properties in each place. Just refer to this.props in your render function. Here's an example:

    import React, { Component } from 'react'; import { AppRegistry, Text, View } from 'react-native'; @@ -26,7 +27,7 @@ class Greeting extends } } -class LotsOfGreetings extends Component { +export default class LotsOfGreetings extends Component { render() { return ( <View style={{alignItems: 'center'}}> @@ -37,8 +38,9 @@ class LotsOfGreetings extends ); } } - -AppRegistry.registerComponent('LotsOfGreetings', () => LotsOfGreetings);

    Using name as a prop lets us customize the Greeting component, so we can reuse that component for each of our greetings. This example also uses the Greeting component in JSX, just like the built-in components. The power to do this is what makes React so cool - if you find yourself wishing that you had a different set of UI primitives to work with, you just invent new ones.

    The other new thing going on here is the View component. A View is useful + +// skip this line if using Create React Native App +AppRegistry.registerComponent('LotsOfGreetings', () => LotsOfGreetings);

    Using name as a prop lets us customize the Greeting component, so we can reuse that component for each of our greetings. This example also uses the Greeting component in JSX, just like the built-in components. The power to do this is what makes React so cool - if you find yourself wishing that you had a different set of UI primitives to work with, you just invent new ones.

    The other new thing going on here is the View component. A View is useful as a container for other components, to help control style and layout.

    With props and the basic Text, Image, and View components, you can build a wide variety of static screens. To learn how to make your app change over time, you need to learn about State.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/pushnotificationios.html b/docs/pushnotificationios.html index e238c24c7cd..359e67a3e6b 100644 --- a/docs/pushnotificationios.html +++ b/docs/pushnotificationios.html @@ -1,7 +1,17 @@ -PushNotificationIOS

    PushNotificationIOS #

    Handle push notifications for your app, including permission handling and +PushNotificationIOS

    PushNotificationIOS #

    + +

    Handle push notifications for your app, including permission handling and icon badge number.

    To get up and running, configure your notifications with Apple -and your server-side system. To get an idea, this is the Parse guide.

    Manually link the PushNotificationIOS library

    • Add the following to your Project: node_modules/react-native/Libraries/PushNotificationIOS/RCTPushNotification.xcodeproj
    • Add the following to Link Binary With Libraries: libRCTPushNotification.a
    • Add the following to your Header Search Paths: -$(SRCROOT)/../node_modules/react-native/Libraries/PushNotificationIOS and set the search to recursive

    Finally, to enable support for notification and register events you need to augment your AppDelegate.

    At the top of your AppDelegate.m:

    #import "RCTPushNotificationManager.h"

    And then in your AppDelegate implementation add the following:

    // Required to register for notifications +and your server-side system.

    Manually link the PushNotificationIOS library

    • Add the following to your Project: node_modules/react-native/Libraries/PushNotificationIOS/RCTPushNotification.xcodeproj
    • Add the following to Link Binary With Libraries: libRCTPushNotification.a

    Finally, to enable support for notification and register events you need to augment your AppDelegate.

    At the top of your AppDelegate.m:

    #import <React/RCTPushNotificationManager.h>

    And then in your AppDelegate implementation add the following:

    // Required to register for notifications - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { [RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings]; @@ -56,206 +66,7 @@ Listening to the notification event and invoking calling this block, pass in the fetch result value that best describes the results of your operation. You must call this handler and should do so as soon as possible. For a list of possible values, see PushNotificationIOS.FetchResult.

    If you do not call this method your background remote notifications could -be throttled, to read more about it see the above documentation link.

    getMessage() #

    An alias for getAlert to get the notification's main message string

    getSound() #

    Gets the sound string from the aps object

    getAlert() #

    Gets the notification's main message from the aps object

    getBadgeCount() #

    Gets the badge count number from the aps object

    getData() #

    Gets the data object on the notif

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - AlertIOS, - PushNotificationIOS, - StyleSheet, - Text, - TouchableHighlight, - View, -} = ReactNative; - -class Button extends React.Component { - render() { - return ( - <TouchableHighlight - underlayColor={'white'} - style={styles.button} - onPress={this.props.onPress}> - <Text style={styles.buttonLabel}> - {this.props.label} - </Text> - </TouchableHighlight> - ); - } -} - -class NotificationExample extends React.Component { - componentWillMount() { - PushNotificationIOS.addEventListener('register', this._onRegistered); - PushNotificationIOS.addEventListener('registrationError', this._onRegistrationError); - PushNotificationIOS.addEventListener('notification', this._onRemoteNotification); - PushNotificationIOS.addEventListener('localNotification', this._onLocalNotification); - - PushNotificationIOS.requestPermissions(); - } - - componentWillUnmount() { - PushNotificationIOS.removeEventListener('register', this._onRegistered); - PushNotificationIOS.removeEventListener('registrationError', this._onRegistrationError); - PushNotificationIOS.removeEventListener('notification', this._onRemoteNotification); - PushNotificationIOS.removeEventListener('localNotification', this._onLocalNotification); - } - - render() { - return ( - <View> - <Button - onPress={this._sendNotification} - label="Send fake notification" - /> - - <Button - onPress={this._sendLocalNotification} - label="Send fake local notification" - /> - </View> - ); - } - - _sendNotification() { - require('RCTDeviceEventEmitter').emit('remoteNotificationReceived', { - aps: { - alert: 'Sample notification', - badge: '+1', - sound: 'default', - category: 'REACT_NATIVE' - }, - }); - } - - _sendLocalNotification() { - require('RCTDeviceEventEmitter').emit('localNotificationReceived', { - aps: { - alert: 'Sample local notification', - badge: '+1', - sound: 'default', - category: 'REACT_NATIVE' - }, - }); - } - - _onRegistered(deviceToken) { - AlertIOS.alert( - 'Registered For Remote Push', - `Device Token: ${deviceToken}`, - [{ - text: 'Dismiss', - onPress: null, - }] - ); - } - - _onRegistrationError(error) { - AlertIOS.alert( - 'Failed To Register For Remote Push', - `Error (${error.code}): ${error.message}`, - [{ - text: 'Dismiss', - onPress: null, - }] - ); - } - - _onRemoteNotification(notification) { - AlertIOS.alert( - 'Push Notification Received', - 'Alert message: ' + notification.getMessage(), - [{ - text: 'Dismiss', - onPress: null, - }] - ); - } - - _onLocalNotification(notification){ - AlertIOS.alert( - 'Local Notification Received', - 'Alert message: ' + notification.getMessage(), - [{ - text: 'Dismiss', - onPress: null, - }] - ); - } -} - -class NotificationPermissionExample extends React.Component { - state: any; - - constructor(props) { - super(props); - this.state = {permissions: null}; - } - - render() { - return ( - <View> - <Button - onPress={this._showPermissions.bind(this)} - label="Show enabled permissions" - /> - <Text> - {JSON.stringify(this.state.permissions)} - </Text> - </View> - ); - } - - _showPermissions() { - PushNotificationIOS.checkPermissions((permissions) => { - this.setState({permissions}); - }); - } -} - -var styles = StyleSheet.create({ - button: { - padding: 10, - alignItems: 'center', - justifyContent: 'center', - }, - buttonLabel: { - color: 'blue', - }, -}); - -exports.title = 'PushNotificationIOS'; -exports.description = 'Apple PushNotification and badge value'; -exports.examples = [ -{ - title: 'Badge Number', - render(): React.Element<any> { - return ( - <View> - <Button - onPress={() => PushNotificationIOS.setApplicationIconBadgeNumber(42)} - label="Set app's icon badge to 42" - /> - <Button - onPress={() => PushNotificationIOS.setApplicationIconBadgeNumber(0)} - label="Clear app's icon badge" - /> - </View> - ); - }, -}, -{ - title: 'Push Notifications', - render(): React.Element<any> { - return <NotificationExample />; - } -}, -{ - title: 'Notifications Permissions', - render(): React.Element<any> { - return <NotificationPermissionExample />; - } -}];
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/refreshcontrol.html b/docs/refreshcontrol.html index fe0c8dc9af5..0a4ac91f38f 100644 --- a/docs/refreshcontrol.html +++ b/docs/refreshcontrol.html @@ -1,4 +1,4 @@ -RefreshControl

    RefreshControl #

    This component is used inside a ScrollView or ListView to add pull to refresh +RefreshControl

    RefreshControl #

    This component is used inside a ScrollView or ListView to add pull to refresh functionality. When the ScrollView is at scrollY: 0, swiping down triggers an onRefresh event.

    Usage example #

    class RefreshableList extends Component { constructor(props) { @@ -32,116 +32,7 @@ triggers an onRefresh event.

    } ... }

    Note: refreshing is a controlled prop, this is why it needs to be set to true -in the onRefresh function otherwise the refresh indicator will stop immediately.

    Props #

    onRefresh?: function #

    Called when the view starts refreshing.

    refreshing: bool #

    Whether the view should be indicating an active refresh.

    androidcolors?: [color] #

    The colors (at least one) that will be used to draw the refresh indicator.

    androidenabled?: bool #

    Whether the pull to refresh functionality is enabled.

    androidprogressBackgroundColor?: color #

    The background color of the refresh indicator.

    androidprogressViewOffset?: number #

    Progress view top offset

    androidsize?: enum(RefreshLayoutConsts.SIZE.DEFAULT, RefreshLayoutConsts.SIZE.LARGE) #

    Size of the refresh indicator, see RefreshControl.SIZE.

    iostintColor?: color #

    The color of the refresh indicator.

    iostitle?: string #

    The title displayed under the refresh indicator.

    iostitleColor?: color #

    Title color.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -const React = require('react'); -const ReactNative = require('react-native'); -const { - ScrollView, - StyleSheet, - RefreshControl, - Text, - TouchableWithoutFeedback, - View, -} = ReactNative; - -const styles = StyleSheet.create({ - row: { - borderColor: 'grey', - borderWidth: 1, - padding: 20, - backgroundColor: '#3a5795', - margin: 5, - }, - text: { - alignSelf: 'center', - color: '#fff', - }, - scrollview: { - flex: 1, - }, -}); - -class Row extends React.Component { - _onClick = () => { - this.props.onClick(this.props.data); - }; - - render() { - return ( - <TouchableWithoutFeedback onPress={this._onClick} > - <View style={styles.row}> - <Text style={styles.text}> - {this.props.data.text + ' (' + this.props.data.clicks + ' clicks)'} - </Text> - </View> - </TouchableWithoutFeedback> - ); - } -} - -class RefreshControlExample extends React.Component { - static title = '<RefreshControl>'; - static description = 'Adds pull-to-refresh support to a scrollview.'; - - state = { - isRefreshing: false, - loaded: 0, - rowData: Array.from(new Array(20)).map( - (val, i) => ({text: 'Initial row ' + i, clicks: 0})), - }; - - _onClick = (row) => { - row.clicks++; - this.setState({ - rowData: this.state.rowData, - }); - }; - - render() { - const rows = this.state.rowData.map((row, ii) => { - return <Row key={ii} data={row} onClick={this._onClick}/>; - }); - return ( - <ScrollView - style={styles.scrollview} - refreshControl={ - <RefreshControl - refreshing={this.state.isRefreshing} - onRefresh={this._onRefresh} - tintColor="#ff0000" - title="Loading..." - titleColor="#00ff00" - colors={['#ff0000', '#00ff00', '#0000ff']} - progressBackgroundColor="#ffff00" - /> - }> - {rows} - </ScrollView> - ); - } - - _onRefresh = () => { - this.setState({isRefreshing: true}); - setTimeout(() => { - // prepend 10 items - const rowData = Array.from(new Array(10)) - .map((val, i) => ({ - text: 'Loaded row ' + (+this.state.loaded + i), - clicks: 0, - })) - .concat(this.state.rowData); - - this.setState({ - loaded: this.state.loaded + 10, - isRefreshing: false, - rowData: rowData, - }); - }, 5000); - }; -} - -module.exports = RefreshControlExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/running-on-device.html b/docs/running-on-device.html index 4fe1f950f04..b92ee31e62e 100644 --- a/docs/running-on-device.html +++ b/docs/running-on-device.html @@ -1,4 +1,4 @@ -Running On Device

    Running On Device #

    It's always a good idea to test your app on an actual device before releasing it to your users. This document will guide you through the necessary steps to run your React Native app on a device.

    +Running On Device

    Running On Device #

    It's always a good idea to test your app on an actual device before releasing it to your users. This document will guide you through the necessary steps to run your React Native app on a device and to get it ready for production.

    - Mobile OS: - iOS - Android Development OS: macOS Linux Windows + Target OS: + iOS + Android +
    -

    A Mac is required in order to build your app for iOS devices.

    +

    Running your app on iOS devices #

    A Mac is required in order to build your app for iOS devices. Alternatively, you can refer to the Quick Start instructions to learn how to build your app using Create React Native App, which will allow you to run your app using the Expo client app.

    -

    Running your app on iOS devices #

    Register for a Apple developer account if you don't have one yet.

    Connect your device to your Mac using a USB to Lightning cable. Navigate to the ios folder in your project, then open the .xcodeproj file within it using Xcode.

    Select your app in the Project Navigator and look for the "General" tab. Go to "Signing" and make sure your Apple developer account is selected.

    Open the "Product" menu from Xcode's menubar, then go to "Destination". Look for and select your device from the list. Xcode will then register your device for development.

    If everything is set up correctly, your device will be listed as the build target in the Xcode toolbar. You can now press the Build and run button or select "Run" from the "Product" menu. Your app will launch on your device shortly.

    If you run into any issues, please take a look at Apple's Launching Your App on a Device docs.

    +

    Running your app on iOS devices #

    Register for a Apple developer account if you don't have one yet.

    1. Plug in your device via USB #

    Connect your iOS device to your Mac using a USB to Lightning cable. Navigate to the ios folder in your project, then open the .xcodeproj file within it using Xcode.

    If this is your first time running an app on your iOS device, you may need to register your device for development. Open the Product menu from Xcode's menubar, then go to Destination. Look for and select your device from the list. Xcode will then register your device for development.

    2. Configure code signing #

    Select your project in the Xcode Project Navigator, then select your main target (it should share the same name as your project). Look for the "General" tab. Go to "Signing" and make sure your Apple developer account or team is selected under the Team dropdown.

    Repeat this step for the Tests target in your project.

    3. Build and Run your app #

    If everything is set up correctly, your device will be listed as the build target in the Xcode toolbar, and it will also appear in the Devices pane (⇧⌘2). You can now press the Build and run button (⌘R) or select Run from the Product menu. Your app will launch on your device shortly.

    If you run into any issues, please take a look at Apple's Launching Your App on a Device docs.

    Running your app on Android devices #

    1. Enable Debugging over USB #

    Most Android devices can only install and run apps downloaded from Google Play, by default. You will need to enable USB Debugging on your device in order to install your app during development.

    To enable USB debugging on your device, you will first need to enable the "Developer options" menu by going to SettingsAbout phone and then tapping the Build number row at the bottom seven times. You can then go back to SettingsDeveloper options to enable "USB debugging".

    2. Plug in your device via USB #

    Let's now set up an Android device to run our React Native projects. Go ahead and plug in your device via USB to your development machine.

    @@ -65,11 +66,11 @@ emulator-5554 offline # Google emulator -

    Connecting to the development server #

    You can also iterate quickly on a device using the development server. You only have to be on the same Wi-Fi network as your computer. Enable Live reloading from the Developer menu and your app will reload whenever your JavaScript code has changed.

    If you have any issues, ensure that your Mac and device are on the same network and can reach each other. Many open wireless networks with captive portals are configured to prevent devices from reaching other devices on the network. You may use your device's Personal Hotspot feature in this case.

    +

    Connecting to the development server #

    You can also iterate quickly on a device using the development server. You only have to be on the same Wi-Fi network as your computer. Shake your device to open the Developer menu, then enable Live Reload. Your app will reload whenever your JavaScript code has changed.

    If you have any issues, ensure that your Mac and device are on the same network and can reach each other. Many open wireless networks with captive portals are configured to prevent devices from reaching other devices on the network. You may use your device's Personal Hotspot feature in this case.

    Connecting to the development server #

    You can also iterate quickly on a device by connecting to the development server running on your development machine. There are several ways of accomplishing this, depending on whether you have access to a USB cable or a Wi-Fi network.

    Method 1: Using adb reverse (recommended) #

    -

    You can use this method if your device is running Android 5.0 (Lollipop), it has USB debugging enabled, and it is connected via USB to your development machine.

    +

    You can use this method if your device is running Android 5.0 (Lollipop) or newer, it has USB debugging enabled, and it is connected via USB to your development machine.

    Run the following in a command prompt:

    $ adb reverse tcp:8081 tcp:8081

    You can now enable Live reloading from the Developer menu. Your app will reload whenever your JavaScript code has changed.

    Method 2: Connect via Wi-Fi #

    You can also connect to the development server over Wi-Fi. You'll first need to install the app on your device using a USB cable, but once that has been done you can debug wirelessly by following these instructions. You'll need your development machine's current IP address before proceeding.

    @@ -81,7 +82,9 @@ emulator-5554 offline # Google emulator
    1. Make sure your laptop and your phone are on the same Wi-Fi network.
    2. Open your React Native app on your device.
    3. You'll see a red screen with an error. This is OK. The following steps will fix that.
    4. Open the in-app Developer menu.
    5. Go to Dev SettingsDebug server host for device.
    6. Type in your machine's IP address and the port of the local dev server (e.g. 10.0.1.1:8081).
    7. Go back to the Developer menu and select Reload JS.

    You can now enable Live reloading from the Developer menu. Your app will reload whenever your JavaScript code has changed.

    -

    Building your app for production #

    You have built a great app using React Native, and you are now itching to release it in the App Store. The process is the same as any other native iOS app, with some additional considerations to take into account.

    Building an app for distribution in the App Store requires using the Release scheme in Xcode. To do this, go to ProductSchemeEdit Scheme (cmd + <), make sure you're in the Run tab from the side, and set the Build Configuration dropdown to Release.

    Apps built for Release will automatically disable the in-app Developer menu, which will prevent your users from inadvertently accessing the menu in production. It will also load the JavaScript locally, so you can put the app on a device and test whilst not connected to the computer.

    Hint

    You can also use the React Native CLI to perform this operation using the option --configuration with the value Release (e.g. react-native run-ios --configuration Release).

    Once built for release, you'll be able to distribute the app to beta testers and submit the app to the App Store.

    App Transport Security #

    App Transport Security is a security feature, added in iOS 9, that rejects all HTTP requests that are not sent over HTTPS. This can result in HTTP traffic being blocked, including the developer React Native server.

    ATS is disabled by default in projects generated using the React Native CLI in order to make development easier. You should re-enable ATS prior to building your app for production by removing the NSAllowsArbitraryLoads entry from your Info.plist file in the ios/ folder.

    To learn more about how to configure ATS on your own Xcode projects, see this post on ATS.

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/running-on-simulator-ios.html b/docs/running-on-simulator-ios.html index b12ecb98429..4bdd69c2e83 100644 --- a/docs/running-on-simulator-ios.html +++ b/docs/running-on-simulator-ios.html @@ -1,4 +1,4 @@ -Running On Simulator

    Running On Simulator #

    Starting the simulator #

    Once you have your React Native project initialized, you can run react-native run-ios inside the newly created project directory. If everything is set up correctly, you should see your new app running in the iOS Simulator shortly.

    Specifying a device #

    You can specify the device the simulator should run with the --simulator flag, followed by the device name as a string. The default is "iPhone 6". If you wish to run your app on an iPhone 4s, just run react-native run-ios --simulator="iPhone 4s".

    The device names correspond to the list of devices available in Xcode. You can check your available devices by running xcrun simctl list devices from the console.

    You can edit the content above on GitHub and send us a pull request!

    Running On Simulator #

    Starting the simulator #

    Once you have your React Native project initialized, you can run react-native run-ios inside the newly created project directory. If everything is set up correctly, you should see your new app running in the iOS Simulator shortly.

    Specifying a device #

    You can specify the device the simulator should run with the --simulator flag, followed by the device name as a string. The default is "iPhone 6". If you wish to run your app on an iPhone 4s, just run react-native run-ios --simulator="iPhone 4s".

    The device names correspond to the list of devices available in Xcode. You can check your available devices by running xcrun simctl list devices from the console.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/scrollview.html b/docs/scrollview.html index 52aa21cac3c..5dafd60e6f4 100644 --- a/docs/scrollview.html +++ b/docs/scrollview.html @@ -1,4 +1,4 @@ -ScrollView

    ScrollView #

    Component that wraps platform ScrollView while providing +ScrollView

    ScrollView #

    Component that wraps platform ScrollView while providing integration with touch locking "responder" system.

    Keep in mind that ScrollViews must have a bounded height in order to work, since they contain unbounded-height children into a bounded container (via a scroll interaction). In order to bound the height of a ScrollView, either @@ -9,7 +9,7 @@ easy to debug.

    Doesn't yet support other contained responders from bl view from becoming the responder.

    <ScrollView> vs <FlatList> - which one to use?

    ScrollView simply renders all its react child components at once. That makes it very easy to understand and use.

    On the other hand, this has a performance downside. Imagine you have a very long list of items you want to display, maybe several screens worth of -content. Creating JS components and native views for everythign all at once, +content. Creating JS components and native views for everything all at once, much of which may not even be shown, will contribute to slow rendering and increased memory usage.

    This is where FlatList comes into play. FlatList renders items lazily, just when they are about to appear, and removes items that scroll way off @@ -25,29 +25,33 @@ wraps all of the child views. Example:

    return ( contentContainer: { paddingVertical: 20 } - });

    horizontal?: bool #

    When true, the scroll view's children are arranged horizontally in a row -instead of vertically in a column. The default value is false.

    keyboardDismissMode?: enum('none', 'interactive', 'on-drag') #

    Determines whether the keyboard gets dismissed in response to a drag. + });

    horizontal?: PropTypes.bool #

    When true, the scroll view's children are arranged horizontally in a row +instead of vertically in a column. The default value is false.

    keyboardDismissMode?: PropTypes.oneOf([ + 'none', // default + 'interactive', + 'on-drag', +]) #

    Determines whether the keyboard gets dismissed in response to a drag. - 'none' (the default), drags do not dismiss the keyboard. - 'on-drag', the keyboard is dismissed when a drag begins. - 'interactive', the keyboard is dismissed interactively with the drag and moves in synchrony with the touch; dragging upwards cancels the dismissal. - On android this is not supported and it will have the same behavior as 'none'.

    keyboardShouldPersistTaps?: enum('always', 'never', 'handled', false, true) #

    Determines when the keyboard should stay visible after a tap.

    • 'never' (the default), tapping outside of the focused text input when the keyboard + On android this is not supported and it will have the same behavior as 'none'.

    keyboardShouldPersistTaps?: PropTypes.oneOf(['always', 'never', 'handled', false, true]) #

    Determines when the keyboard should stay visible after a tap.

    • 'never' (the default), tapping outside of the focused text input when the keyboard is up dismisses the keyboard. When this happens, children won't receive the tap.
    • 'always', the keyboard will not dismiss automatically, and the scroll view will not catch taps, but children of the scroll view can catch taps.
    • 'handled', the keyboard will not dismiss automatically when the tap was handled by -a children, (or captured by an ancestor).
    • false, deprecated, use 'never' instead
    • true, deprecated, use 'always' instead

    onContentSizeChange?: function #

    Called when scrollable content view of the ScrollView changes.

    Handler function is passed the content width and content height as parameters: +a children, (or captured by an ancestor).

  • false, deprecated, use 'never' instead
  • true, deprecated, use 'always' instead
  • onContentSizeChange?: PropTypes.func #

    Called when scrollable content view of the ScrollView changes.

    Handler function is passed the content width and content height as parameters: (contentWidth, contentHeight)

    It's implemented using onLayout handler attached to the content container -which this ScrollView renders.

    onScroll?: function #

    Fires at most once per frame during scrolling. The frequency of the -events can be controlled using the scrollEventThrottle prop.

    pagingEnabled?: bool #

    When true, the scroll view stops on multiples of the scroll view's size +which this ScrollView renders.

    onScroll?: PropTypes.func #

    Fires at most once per frame during scrolling. The frequency of the +events can be controlled using the scrollEventThrottle prop.

    pagingEnabled?: PropTypes.bool #

    When true, the scroll view stops on multiples of the scroll view's size when scrolling. This can be used for horizontal pagination. The default -value is false.

    refreshControl?: element #

    A RefreshControl component, used to provide pull-to-refresh +value is false.

    refreshControl?: PropTypes.element #

    A RefreshControl component, used to provide pull-to-refresh functionality for the ScrollView. Only works for vertical ScrollViews -(horizontal prop must be false).

    See RefreshControl.

    removeClippedSubviews?: bool #

    Experimental: When true, offscreen child views (whose overflow value is +(horizontal prop must be false).

    See RefreshControl.

    removeClippedSubviews?: PropTypes.bool #

    Experimental: When true, offscreen child views (whose overflow value is hidden) are removed from their native backing superview when offscreen. This can improve scrolling performance on long lists. The default value is -true.

    scrollEnabled?: bool #

    When false, the content does not scroll. -The default value is true.

    showsHorizontalScrollIndicator?: bool #

    When true, shows a horizontal scroll indicator. -The default value is true.

    showsVerticalScrollIndicator?: bool #

    When true, shows a vertical scroll indicator. -The default value is true.

    stickyHeaderIndices?: [number] #

    An array of child indices determining which children get docked to the +true.

    scrollEnabled?: PropTypes.bool #

    When false, the content does not scroll. +The default value is true.

    showsHorizontalScrollIndicator?: PropTypes.bool #

    When true, shows a horizontal scroll indicator. +The default value is true.

    showsVerticalScrollIndicator?: PropTypes.bool #

    When true, shows a vertical scroll indicator. +The default value is true.

    stickyHeaderIndices?: PropTypes.arrayOf(PropTypes.number) #

    An array of child indices determining which children get docked to the top of the screen when scrolling. For example, passing stickyHeaderIndices={[0]} will cause the first child to be fixed to the top of the scroll view. This property is not supported in conjunction @@ -57,38 +61,49 @@ This adds a drop shadow to the item and affects z-order for overlapping views. Only supported on Android 5.0+, has no effect on earlier versions.

    androidendFillColor?: color #

    Sometimes a scrollview takes up more space than its content fills. When this is the case, this prop will fill the rest of the scrollview with a color to avoid setting a background and creating unnecessary overdraw. This is an advanced optimization -that is not needed in the general case.

    androidoverScrollMode?: enum('auto', 'always', 'never') #

    Used to override default value of overScroll mode.

    Possible values:

    • 'auto' - Default value, allow a user to over-scroll -this view only if the content is large enough to meaningfully scroll.
    • 'always' - Always allow a user to over-scroll this view.
    • 'never' - Never allow a user to over-scroll this view.

    androidscrollPerfTag?: string #

    Tag used to log scroll performance on this scroll view. Will force +that is not needed in the general case.

    androidoverScrollMode?: PropTypes.oneOf([ + 'auto', + 'always', + 'never', +]) #

    Used to override default value of overScroll mode.

    Possible values:

    • 'auto' - Default value, allow a user to over-scroll +this view only if the content is large enough to meaningfully scroll.
    • 'always' - Always allow a user to over-scroll this view.
    • 'never' - Never allow a user to over-scroll this view.

    androidscrollPerfTag?: PropTypes.string #

    Tag used to log scroll performance on this scroll view. Will force momentum events to be turned on (see sendMomentumEvents). This doesn't do anything out of the box and you need to implement a custom native -FpsListener for it to be useful.

    iosalwaysBounceHorizontal?: bool #

    When true, the scroll view bounces horizontally when it reaches the end +FpsListener for it to be useful.

    iosalwaysBounceHorizontal?: PropTypes.bool #

    When true, the scroll view bounces horizontally when it reaches the end even if the content is smaller than the scroll view itself. The default -value is true when horizontal={true} and false otherwise.

    iosalwaysBounceVertical?: bool #

    When true, the scroll view bounces vertically when it reaches the end +value is true when horizontal={true} and false otherwise.

    iosalwaysBounceVertical?: PropTypes.bool #

    When true, the scroll view bounces vertically when it reaches the end even if the content is smaller than the scroll view itself. The default -value is false when horizontal={true} and true otherwise.

    iosautomaticallyAdjustContentInsets?: bool #

    Controls whether iOS should automatically adjust the content inset +value is false when horizontal={true} and true otherwise.

    iosautomaticallyAdjustContentInsets?: PropTypes.bool #

    Controls whether iOS should automatically adjust the content inset for scroll views that are placed behind a navigation bar or -tab bar/ toolbar. The default value is true.

    iosbounces?: bool #

    When true, the scroll view bounces when it reaches the end of the +tab bar/ toolbar. The default value is true.

    iosbounces?: PropTypes.bool #

    When true, the scroll view bounces when it reaches the end of the content if the content is larger then the scroll view along the axis of the scroll direction. When false, it disables all bouncing even if -the alwaysBounce* props are true. The default value is true.

    iosbouncesZoom?: bool #

    When true, gestures can drive zoom past min/max and the zoom will animate +the alwaysBounce* props are true. The default value is true.

    iosbouncesZoom?: PropTypes.bool #

    When true, gestures can drive zoom past min/max and the zoom will animate to the min/max value at gesture end, otherwise the zoom will not exceed -the limits.

    ioscanCancelContentTouches?: bool #

    When false, once tracking starts, won't try to drag if the touch moves. -The default value is true.

    ioscenterContent?: bool #

    When true, the scroll view automatically centers the content when the +the limits.

    ioscanCancelContentTouches?: PropTypes.bool #

    When false, once tracking starts, won't try to drag if the touch moves. +The default value is true.

    ioscenterContent?: PropTypes.bool #

    When true, the scroll view automatically centers the content when the content is smaller than the scroll view bounds; when the content is larger than the scroll view, this property has no effect. The default value is false.

    ioscontentInset?: {top: number, left: number, bottom: number, right: number} #

    The amount by which the scroll view content is inset from the edges of the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}.

    ioscontentOffset?: PointPropType #

    Used to manually set the starting scroll offset. -The default value is {x: 0, y: 0}.

    iosdecelerationRate?: enum('fast', 'normal'), number #

    A floating-point number that determines how quickly the scroll view +The default value is {x: 0, y: 0}.

    iosdecelerationRate?: PropTypes.oneOfType([ + PropTypes.oneOf(['fast', 'normal']), + PropTypes.number, +]) #

    A floating-point number that determines how quickly the scroll view decelerates after the user lifts their finger. You may also use string shortcuts "normal" and "fast" which match the underlying iOS settings for UIScrollViewDecelerationRateNormal and UIScrollViewDecelerationRateFast respectively. - normal: 0.998 (the default) - - fast: 0.99

    iosdirectionalLockEnabled?: bool #

    When true, the ScrollView will try to lock to only vertical or horizontal -scrolling while dragging. The default value is false.

    iosindicatorStyle?: enum('default', 'black', 'white') #

    The style of the scroll indicators. + - fast: 0.99

    iosdirectionalLockEnabled?: PropTypes.bool #

    When true, the ScrollView will try to lock to only vertical or horizontal +scrolling while dragging. The default value is false.

    iosindicatorStyle?: PropTypes.oneOf([ + 'default', // default + 'black', + 'white', +]) #

    The style of the scroll indicators. - default (the default), same as black. - black, scroll indicator is black. This style is good against a light background. - - white, scroll indicator is white. This style is good against a dark background.

    iosmaximumZoomScale?: number #

    The maximum allowed zoom scale. The default value is 1.0.

    iosminimumZoomScale?: number #

    The minimum allowed zoom scale. The default value is 1.0.

    iosonScrollAnimationEnd?: function #

    Called when a scrolling animation ends.

    iosscrollEventThrottle?: number #

    This controls how often the scroll event will be fired while scrolling + - white, scroll indicator is white. This style is good against a dark background.

    iosmaximumZoomScale?: PropTypes.number #

    The maximum allowed zoom scale. The default value is 1.0.

    iosminimumZoomScale?: PropTypes.number #

    The minimum allowed zoom scale. The default value is 1.0.

    iosonScrollAnimationEnd?: PropTypes.func #

    Called when a scrolling animation ends.

    iosscrollEventThrottle?: PropTypes.number #

    This controls how often the scroll event will be fired while scrolling (as a time interval in ms). A lower number yields better accuracy for code that is tracking the scroll position, but can lead to scroll performance problems due to the volume of information being send over the bridge. @@ -98,169 +113,24 @@ scroll position tracking, set this value higher to limit the information being sent across the bridge. The default value is zero, which results in the scroll event being sent only once each time the view is scrolled.

    iosscrollIndicatorInsets?: {top: number, left: number, bottom: number, right: number} #

    The amount by which the scroll view indicators are inset from the edges of the scroll view. This should normally be set to the same value as -the contentInset. Defaults to {0, 0, 0, 0}.

    iosscrollsToTop?: bool #

    When true, the scroll view scrolls to top when the status bar is tapped. -The default value is true.

    iossnapToAlignment?: enum('start', 'center', 'end') #

    When snapToInterval is set, snapToAlignment will define the relationship +the contentInset. Defaults to {0, 0, 0, 0}.

    iosscrollsToTop?: PropTypes.bool #

    When true, the scroll view scrolls to top when the status bar is tapped. +The default value is true.

    iossnapToAlignment?: PropTypes.oneOf([ + 'start', // default + 'center', + 'end', +]) #

    When snapToInterval is set, snapToAlignment will define the relationship of the snapping to the scroll view. - start (the default) will align the snap at the left (horizontal) or top (vertical) - center will align the snap in the center - - end will align the snap at the right (horizontal) or bottom (vertical)

    iossnapToInterval?: number #

    When set, causes the scroll view to stop at multiples of the value of + - end will align the snap at the right (horizontal) or bottom (vertical)

    iossnapToInterval?: PropTypes.number #

    When set, causes the scroll view to stop at multiples of the value of snapToInterval. This can be used for paginating through children that have lengths smaller than the scroll view. Used in combination -with snapToAlignment.

    ioszoomScale?: number #

    The current scale of the scroll view content. The default value is 1.0.

    Methods #

    scrollTo(y?: number, object, x?: number, animated?: boolean) #

    Scrolls to a given x, y offset, either immediately or with a smooth animation.

    Example:

    scrollTo({x: 0; y: 0; animated: true})

    Note: The weird function signature is due to the fact that, for historical reasons, +with snapToAlignment.

    ioszoomScale?: PropTypes.number #

    The current scale of the scroll view content. The default value is 1.0.

    Methods #

    scrollTo(y?: number, object, x?: number, animated?: boolean) #

    Scrolls to a given x, y offset, either immediately or with a smooth animation.

    Example:

    scrollTo({x: 0, y: 0, animated: true})

    Note: The weird function signature is due to the fact that, for historical reasons, the function also accepts separate arguments as an alternative to the options object. This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.

    scrollToEnd(options?: object) #

    If this is a vertical ScrollView scrolls to the bottom. If this is a horizontal ScrollView scrolls to the right.

    Use scrollToEnd({animated: true}) for smooth animated scrolling, scrollToEnd({animated: false}) for immediate scrolling. -If no options are passed, animated defaults to true.

    scrollWithoutAnimationTo(y, x) #

    Deprecated, use scrollTo instead.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - ScrollView, - StyleSheet, - Text, - TouchableOpacity, - View, - Image -} = ReactNative; - -exports.displayName = 'ScrollViewExample'; -exports.title = '<ScrollView>'; -exports.description = 'Component that enables scrolling through child components'; -exports.examples = [ -{ - title: '<ScrollView>', - description: 'To make content scrollable, wrap it within a <ScrollView> component', - render: function() { - var _scrollView: ScrollView; - return ( - <View> - <ScrollView - ref={(scrollView) => { _scrollView = scrollView; }} - automaticallyAdjustContentInsets={false} - onScroll={() => { console.log('onScroll!'); }} - scrollEventThrottle={200} - style={styles.scrollView}> - {THUMB_URLS.map(createThumbRow)} - </ScrollView> - <TouchableOpacity - style={styles.button} - onPress={() => { _scrollView.scrollTo({y: 0}); }}> - <Text>Scroll to top</Text> - </TouchableOpacity> - <TouchableOpacity - style={styles.button} - onPress={() => { _scrollView.scrollToEnd({animated: true}); }}> - <Text>Scroll to bottom</Text> - </TouchableOpacity> - </View> - ); - } -}, { - title: '<ScrollView> (horizontal = true)', - description: 'You can display <ScrollView>\'s child components horizontally rather than vertically', - render: function() { - - function renderScrollView(title: string, addtionalStyles: StyleSheet) { - var _scrollView: ScrollView; - return ( - <View style={addtionalStyles}> - <Text style={styles.text}>{title}</Text> - <ScrollView - ref={(scrollView) => { _scrollView = scrollView; }} - automaticallyAdjustContentInsets={false} - horizontal={true} - style={[styles.scrollView, styles.horizontalScrollView]}> - {THUMB_URLS.map(createThumbRow)} - </ScrollView> - <TouchableOpacity - style={styles.button} - onPress={() => { _scrollView.scrollTo({x: 0}); }}> - <Text>Scroll to start</Text> - </TouchableOpacity> - <TouchableOpacity - style={styles.button} - onPress={() => { _scrollView.scrollToEnd({animated: true}); }}> - <Text>Scroll to end</Text> - </TouchableOpacity> - </View> - ); - } - - return ( - <View> - {renderScrollView('LTR layout', {direction: 'ltr'})} - {renderScrollView('RTL layout', {direction: 'rtl'})} - </View> - ); - } -}]; - -class Thumb extends React.Component { - shouldComponentUpdate(nextProps, nextState) { - return false; - } - - render() { - return ( - <View style={styles.thumb}> - <Image style={styles.img} source={this.props.source} /> - </View> - ); - } -} - -var THUMB_URLS = [ - require('./Thumbnails/like.png'), - require('./Thumbnails/dislike.png'), - require('./Thumbnails/call.png'), - require('./Thumbnails/fist.png'), - require('./Thumbnails/bandaged.png'), - require('./Thumbnails/flowers.png'), - require('./Thumbnails/heart.png'), - require('./Thumbnails/liking.png'), - require('./Thumbnails/party.png'), - require('./Thumbnails/poke.png'), - require('./Thumbnails/superlike.png'), - require('./Thumbnails/victory.png'), -]; - -THUMB_URLS = THUMB_URLS.concat(THUMB_URLS); // double length of THUMB_URLS - -var createThumbRow = (uri, i) => <Thumb key={i} source={uri} />; - -var styles = StyleSheet.create({ - scrollView: { - backgroundColor: '#eeeeee', - height: 300, - }, - horizontalScrollView: { - height: 106, - }, - text: { - fontSize: 16, - fontWeight: 'bold', - margin: 5, - }, - button: { - margin: 5, - padding: 5, - alignItems: 'center', - backgroundColor: '#cccccc', - borderRadius: 3, - }, - thumb: { - margin: 5, - padding: 5, - backgroundColor: '#cccccc', - borderRadius: 3, - minWidth: 96, - }, - img: { - width: 64, - height: 64, - } -});
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/sectionlist.html b/docs/sectionlist.html index 6e386f642c1..dabfb095aa3 100644 --- a/docs/sectionlist.html +++ b/docs/sectionlist.html @@ -1,36 +1,47 @@ -SectionList

    SectionList #

    A performant interface for rendering sectioned lists, supporting the most handy features:

    • Fully cross-platform.
    • Configurable viewability callbacks.
    • List header support.
    • List footer support.
    • Item separator support.
    • Section header support.
    • Section separator support.
    • Heterogeneous data and item rendering support.
    • Pull to Refresh.
    • Scroll loading.

    If you don't need section support and want a simpler interface, use -<FlatList>.

    If you need sticky section header support, use ListView for now.

    Simple Examples:

    <SectionList - renderItem={({item}) => <ListItem title={item.title}} - renderSectionHeader={({section}) => <H1 title={section.key} />} +SectionList

    SectionList #

    A performant interface for rendering sectioned lists, supporting the most handy features:

    • Fully cross-platform.
    • Configurable viewability callbacks.
    • List header support.
    • List footer support.
    • Item separator support.
    • Section header support.
    • Section separator support.
    • Heterogeneous data and item rendering support.
    • Pull to Refresh.
    • Scroll loading.

    If you don't need section support and want a simpler interface, use +<FlatList>.

    Simple Examples:

    <SectionList + renderItem={({item}) => <ListItem title={item.title} />} + renderSectionHeader={({section}) => <H1 title={section.title} />} sections={[ // homogenous rendering between sections - {data: [...], key: ...}, - {data: [...], key: ...}, - {data: [...], key: ...}, + {data: [...], title: ...}, + {data: [...], title: ...}, + {data: [...], title: ...}, ]} /> <SectionList sections={[ // heterogeneous rendering between sections - {data: [...], key: ..., renderItem: ...}, - {data: [...], key: ..., renderItem: ...}, - {data: [...], key: ..., renderItem: ...}, + {data: [...], title: ..., renderItem: ...}, + {data: [...], title: ..., renderItem: ...}, + {data: [...], title: ..., renderItem: ...}, ]} -/>

    This is a convenience wrapper around <VirtualizedList>, -and thus inherits the following caveats:

    • Internal state is not preserved when content scrolls out of the render window. Make sure all +/>

    This is a convenience wrapper around <VirtualizedList>, +and thus inherits it's props (as well as those of ScrollView) that aren't explicitly listed +here, along with the following caveats:

    • Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.
    • This is a PureComponent which means that it will not re-render if props remain shallow- -equal. Make sure that everything your renderItem function depends on is passed as a prop that -is not === after updates, otherwise your UI may not update on changes. This includes the -data prop and parent component state.
    • In order to constrain memory and enable smooth scrolling, content is rendered asynchronously +equal. Make sure that everything your renderItem function depends on is passed as a prop +(e.g. extraData) that is not === after updates, otherwise your UI may not update on +changes. This includes the data prop and parent component state.
    • In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.
    • By default, the list looks for a key prop on each item and uses that for the React key. -Alternatively, you can provide a custom keyExtractor prop.

    Props #

    ItemSeparatorComponent?: ?ReactClass<any> #

    Rendered in between adjacent Items within each section.

    ListFooterComponent?: ?ReactClass<any> #

    Rendered at the very end of the list.

    ListHeaderComponent?: ?ReactClass<any> #

    Rendered at the very beginning of the list.

    SectionSeparatorComponent?: ?ReactClass<any> #

    Rendered in between each section.

    extraData?: any #

    A marker property for telling the list to re-render (since it implements PureComponent). If +Alternatively, you can provide a custom keyExtractor prop.

    Props #

    ItemSeparatorComponent?: ?ReactClass<any> #

    Rendered in between each item, but not at the top or bottom. By default, highlighted, +section, and [leading/trailing][Item/Separator] props are provided. renderItem provides +separators.highlight/unhighlight which will update the highlighted prop, but you can also +add custom props with separators.updateProps.

    ListEmptyComponent?: ?ReactClass<any> | React.Element<any> #

    Rendered when the list is empty. Can be a React Component Class, a render function, or +a rendered element.

    ListFooterComponent?: ?ReactClass<any> | React.Element<any> #

    Rendered at the very end of the list. Can be a React Component Class, a render function, or +a rendered element.

    ListHeaderComponent?: ?ReactClass<any> | React.Element<any> #

    Rendered at the very beginning of the list. Can be a React Component Class, a render function, or +a rendered element.

    SectionSeparatorComponent?: ?ReactClass<any> #

    Rendered at the top and bottom of each section (note this is different from +ItemSeparatorComponent which is only rendered between items). These are intended to separate +sections from the headers above and below and typically have the same highlight response as +ItemSeparatorComponent. Also receives highlighted, [leading/trailing][Item/Separator], +and any custom props from separators.updateProps.

    extraData?: any #

    A marker property for telling the list to re-render (since it implements PureComponent). If any of your renderItem, Header, Footer, etc. functions depend on anything outside of the data prop, stick it here and treat it immutably.

    initialNumToRender: number #

    How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order to improve perceived performance of scroll-to-top actions.

    keyExtractor: (item: Item, index: number) => string #

    Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks item.key, then -falls back to using the index, like react does.

    onEndReached?: ?(info: {distanceFromEnd: number}) => void #

    Called once when the scroll position gets within onEndReachedThreshold of the rendered +falls back to using the index, like react does.

    legacyImplementation?: ?boolean #

    onEndReached?: ?(info: {distanceFromEnd: number}) => void #

    Called once when the scroll position gets within onEndReachedThreshold of the rendered content.

    onEndReachedThreshold?: ?number #

    How far from the end (in units of visible length of the list) the bottom edge of the list must be from the end of the content to trigger the onEndReached callback. Thus a value of 0.5 will trigger onEndReached when the end of the content is @@ -39,190 +50,29 @@ sure to also set the refreshing prop correctly.

    #

    Called when the viewability of rows changes, as defined by the -viewabilityConfig prop.

    refreshing?: ?boolean #

    Set this true while waiting for new data from a refresh.

    renderItem: (info: {item: Item, index: number}) => ?React.Element<any> #

    Default renderer for every item in every section. Can be over-ridden on a per-section basis.

    renderSectionHeader?: ?(info: {section: SectionT}) => ?React.Element<any> #

    Rendered at the top of each section. Sticky headers are not yet supported.

    sections: Array<SectionT> #

    stickySectionHeadersEnabled?: boolean #

    Makes section headers stick to the top of the screen until the next one pushes it off. Only -enabled by default on iOS because that is the platform standard there.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -const React = require('react'); -const ReactNative = require('react-native'); -const { - Animated, - SectionList, - StyleSheet, - Text, - View, -} = ReactNative; - -const UIExplorerPage = require('./UIExplorerPage'); - -const infoLog = require('infoLog'); - -const { - HeaderComponent, - FooterComponent, - ItemComponent, - PlainInput, - SeparatorComponent, - Spindicator, - genItemData, - pressItem, - renderSmallSwitchOption, - renderStackedItem, -} = require('./ListExampleShared'); - -const AnimatedSectionList = Animated.createAnimatedComponent(SectionList); - -const VIEWABILITY_CONFIG = { - minimumViewTime: 3000, - viewAreaCoveragePercentThreshold: 100, - waitForInteraction: true, -}; - -const renderSectionHeader = ({section}) => ( - <View> - <Text style={styles.headerText}>SECTION HEADER: {section.key}</Text> - <SeparatorComponent /> - </View> -); - -const CustomSeparatorComponent = ({text}) => ( - <View> - <SeparatorComponent /> - <Text style={styles.separatorText}>{text}</Text> - <SeparatorComponent /> - </View> -); - -class SectionListExample extends React.PureComponent { - static title = '<SectionList>'; - static description = 'Performant, scrollable list of data.'; - - state = { - data: genItemData(1000), - debug: false, - filterText: '', - logViewable: false, - virtualized: true, - }; - - _scrollPos = new Animated.Value(0); - _scrollSinkY = Animated.event( - [{nativeEvent: { contentOffset: { y: this._scrollPos } }}], - {useNativeDriver: true}, - ); - - render() { - const filterRegex = new RegExp(String(this.state.filterText), 'i'); - const filter = (item) => ( - filterRegex.test(item.text) || filterRegex.test(item.title) - ); - const filteredData = this.state.data.filter(filter); - const filteredSectionData = []; - let startIndex = 0; - const endIndex = filteredData.length - 1; - for (let ii = 10; ii <= endIndex + 10; ii += 10) { - filteredSectionData.push({ - key: `${filteredData[startIndex].key} - ${filteredData[Math.min(ii - 1, endIndex)].key}`, - data: filteredData.slice(startIndex, ii), - }); - startIndex = ii; - } - return ( - <UIExplorerPage - noSpacer={true} - noScroll={true}> - <View style={styles.searchRow}> - <PlainInput - onChangeText={filterText => { - this.setState(() => ({filterText})); - }} - placeholder="Search..." - value={this.state.filterText} - /> - <View style={styles.optionSection}> - {renderSmallSwitchOption(this, 'virtualized')} - {renderSmallSwitchOption(this, 'logViewable')} - {renderSmallSwitchOption(this, 'debug')} - <Spindicator value={this._scrollPos} /> - </View> - </View> - <SeparatorComponent /> - <AnimatedSectionList - ListHeaderComponent={HeaderComponent} - ListFooterComponent={FooterComponent} - SectionSeparatorComponent={() => - <CustomSeparatorComponent text="SECTION SEPARATOR" /> - } - ItemSeparatorComponent={() => - <CustomSeparatorComponent text="ITEM SEPARATOR" /> - } - debug={this.state.debug} - enableVirtualization={this.state.virtualized} - onRefresh={() => alert('onRefresh: nothing to refresh :P')} - onScroll={this._scrollSinkY} - onViewableItemsChanged={this._onViewableItemsChanged} - refreshing={false} - renderItem={this._renderItemComponent} - renderSectionHeader={renderSectionHeader} - sections={[ - {renderItem: renderStackedItem, key: 's1', data: [ - {title: 'Item In Header Section', text: 'Section s1', key: '0'}, - ]}, - {key: 's2', data: [ - {noImage: true, title: '1st item', text: 'Section s2', key: '0'}, - {noImage: true, title: '2nd item', text: 'Section s2', key: '1'}, - ]}, - ...filteredSectionData, - ]} - viewabilityConfig={VIEWABILITY_CONFIG} - /> - </UIExplorerPage> - ); - } - _renderItemComponent = ({item}) => ( - <ItemComponent item={item} onPress={this._pressItem} /> - ); - // This is called when items change viewability by scrolling into our out of - // the viewable area. - _onViewableItemsChanged = (info: { - changed: Array<{ - key: string, - isViewable: boolean, - item: {columns: Array<*>}, - index: ?number, - section?: any - }>}, - ) => { - // Impressions can be logged here - if (this.state.logViewable) { - infoLog('onViewableItemsChanged: ', info.changed.map((v: Object) => ( - {...v, item: '...', section: v.section.key} - ))); - } - }; - _pressItem = (index: number) => { - pressItem(this, index); - }; -} - -const styles = StyleSheet.create({ - headerText: { - padding: 4, - }, - optionSection: { - flexDirection: 'row', - }, - searchRow: { - paddingHorizontal: 10, - }, - separatorText: { - color: 'gray', - alignSelf: 'center', - padding: 4, - fontSize: 9, - }, -}); - -module.exports = SectionListExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/segmentedcontrolios.html b/docs/segmentedcontrolios.html index a3ae6841e4e..bd6f6e17b87 100644 --- a/docs/segmentedcontrolios.html +++ b/docs/segmentedcontrolios.html @@ -1,4 +1,4 @@ -SegmentedControlIOS

    SegmentedControlIOS #

    Use SegmentedControlIOS to render a UISegmentedControl iOS.

    Programmatically changing selected index #

    The selected index can be changed on the fly by assigning the +SegmentedControlIOS

    SegmentedControlIOS #

    Use SegmentedControlIOS to render a UISegmentedControl iOS.

    Programmatically changing selected index #

    The selected index can be changed on the fly by assigning the selectIndex prop to a state variable, then changing that variable. Note that the state variable would need to be updated as the user selects a value and changes the index, as shown in the example below.

    <SegmentedControlIOS @@ -7,163 +7,11 @@ selects a value and changes the index, as shown in the example below.

    ={(event) => { this.setState({selectedIndex: event.nativeEvent.selectedSegmentIndex}); }} -/>

    Props #

    enabled?: bool #

    If false the user won't be able to interact with the control. -Default value is true.

    momentary?: bool #

    If true, then selecting a segment won't persist visually. -The onValueChange callback will still work as expected.

    onChange?: function #

    Callback that is called when the user taps a segment; -passes the event as an argument

    onValueChange?: function #

    Callback that is called when the user taps a segment; -passes the segment's value as an argument

    selectedIndex?: number #

    The index in props.values of the segment to be (pre)selected.

    tintColor?: string #

    Accent color of the control.

    values?: [string] #

    The labels for the control's segment buttons, in order.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - SegmentedControlIOS, - Text, - View, - StyleSheet -} = ReactNative; - -class BasicSegmentedControlExample extends React.Component { - render() { - return ( - <View> - <View style={{marginBottom: 10}}> - <SegmentedControlIOS values={['One', 'Two']} /> - </View> - <View> - <SegmentedControlIOS values={['One', 'Two', 'Three', 'Four', 'Five']} /> - </View> - </View> - ); - } -} - -class PreSelectedSegmentedControlExample extends React.Component { - render() { - return ( - <View> - <View> - <SegmentedControlIOS values={['One', 'Two']} selectedIndex={0} /> - </View> - </View> - ); - } -} - -class MomentarySegmentedControlExample extends React.Component { - render() { - return ( - <View> - <View> - <SegmentedControlIOS values={['One', 'Two']} momentary={true} /> - </View> - </View> - ); - } -} - -class DisabledSegmentedControlExample extends React.Component { - render() { - return ( - <View> - <View> - <SegmentedControlIOS enabled={false} values={['One', 'Two']} selectedIndex={1} /> - </View> - </View> - ); - } -} - -class ColorSegmentedControlExample extends React.Component { - render() { - return ( - <View> - <View style={{marginBottom: 10}}> - <SegmentedControlIOS tintColor="#ff0000" values={['One', 'Two', 'Three', 'Four']} selectedIndex={0} /> - </View> - <View> - <SegmentedControlIOS tintColor="#00ff00" values={['One', 'Two', 'Three']} selectedIndex={1} /> - </View> - </View> - ); - } -} - -class EventSegmentedControlExample extends React.Component { - state = { - values: ['One', 'Two', 'Three'], - value: 'Not selected', - selectedIndex: undefined - }; - - render() { - return ( - <View> - <Text style={styles.text} > - Value: {this.state.value} - </Text> - <Text style={styles.text} > - Index: {this.state.selectedIndex} - </Text> - <SegmentedControlIOS - values={this.state.values} - selectedIndex={this.state.selectedIndex} - onChange={this._onChange} - onValueChange={this._onValueChange} /> - </View> - ); - } - - _onChange = (event) => { - this.setState({ - selectedIndex: event.nativeEvent.selectedSegmentIndex, - }); - }; - - _onValueChange = (value) => { - this.setState({ - value: value, - }); - }; -} - -var styles = StyleSheet.create({ - text: { - fontSize: 14, - textAlign: 'center', - fontWeight: '500', - margin: 10, - }, -}); - -exports.title = '<SegmentedControlIOS>'; -exports.displayName = 'SegmentedControlExample'; -exports.description = 'Native segmented control'; -exports.examples = [ - { - title: 'Segmented controls can have values', - render(): React.Element<any> { return <BasicSegmentedControlExample />; } - }, - { - title: 'Segmented controls can have a pre-selected value', - render(): React.Element<any> { return <PreSelectedSegmentedControlExample />; } - }, - { - title: 'Segmented controls can be momentary', - render(): React.Element<any> { return <MomentarySegmentedControlExample />; } - }, - { - title: 'Segmented controls can be disabled', - render(): React.Element<any> { return <DisabledSegmentedControlExample />; } - }, - { - title: 'Custom colors can be provided', - render(): React.Element<any> { return <ColorSegmentedControlExample />; } - }, - { - title: 'Change events can be detected', - render(): React.Element<any> { return <EventSegmentedControlExample />; } - } -];
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/settings.html b/docs/settings.html index fe610828528..47cfd221e96 100644 --- a/docs/settings.html +++ b/docs/settings.html @@ -1,4 +1,4 @@ -Settings

    Settings #

    Methods #

    static get(key) #

    static set(settings) #

    static watchKeys(keys, callback) #

    static clearWatch(watchId) #

    Properties #

    You can edit the content above on GitHub and send us a pull request!

    Settings #

    Methods #

    static get(key) #

    static set(settings) #

    static watchKeys(keys, callback) #

    static clearWatch(watchId) #

    Properties #

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/shadow-props.html b/docs/shadow-props.html index dd9b8dfcde1..06ec9819271 100644 --- a/docs/shadow-props.html +++ b/docs/shadow-props.html @@ -1,4 +1,4 @@ -Shadow Props

    Shadow Props #

    Props #

    iosshadowColor?: color #

    Sets the drop shadow color

    iosshadowOffset?: {width: number, height: number} #

    Sets the drop shadow offset

    iosshadowOpacity?: number #

    Sets the drop shadow opacity (multiplied by the color's alpha component)

    iosshadowRadius?: number #

    Sets the drop shadow blur radius

    You can edit the content above on GitHub and send us a pull request!

    Shadow Props #

    Props #

    iosshadowColor?: color #

    Sets the drop shadow color

    iosshadowOffset?: {width: number, height: number} #

    Sets the drop shadow offset

    iosshadowOpacity?: number #

    Sets the drop shadow opacity (multiplied by the color's alpha component)

    iosshadowRadius?: number #

    Sets the drop shadow blur radius

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/share.html b/docs/share.html index 7e0496a4eff..a726cf2c091 100644 --- a/docs/share.html +++ b/docs/share.html @@ -1,115 +1,7 @@ -Share

    Share #

    Methods #

    static share(content, options) #

    Open a dialog to share text content.

    In iOS, Returns a Promise which will be invoked an object containing action, activityType. +Share

    Share #

    Methods #

    static share(content, options) #

    Open a dialog to share text content.

    In iOS, Returns a Promise which will be invoked an object containing action, activityType. If the user dismissed the dialog, the Promise will still be resolved with action being Share.dismissedAction and all the other keys being undefined.

    In Android, Returns a Promise which always be resolved with action being Share.sharedAction.

    Content #

    • message - a message to share
    • title - title of the message

    iOS #

    • url - an URL to share

    At least one of URL and message is required.

    Options #

    iOS #

    • excludedActivityTypes
    • tintColor

    Android #

    • dialogTitle

    static sharedAction() #

    The content was successfully shared.

    static dismissedAction() #

    The dialog has been dismissed. -@platform ios

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - StyleSheet, - View, - Text, - TouchableHighlight, - Share, -} = ReactNative; - -exports.framework = 'React'; -exports.title = 'Share'; -exports.description = 'Share data with other Apps.'; -exports.examples = [{ - title: 'Share Text Content', - render() { - return <ShareMessageExample />; - } -}]; - -class ShareMessageExample extends React.Component { - _shareMessage: Function; - _shareText: Function; - _showResult: Function; - state: any; - - constructor(props) { - super(props); - - this._shareMessage = this._shareMessage.bind(this); - this._shareText = this._shareText.bind(this); - this._showResult = this._showResult.bind(this); - - this.state = { - result: '' - }; - } - - render() { - return ( - <View> - <TouchableHighlight style={styles.wrapper} - onPress={this._shareMessage}> - <View style={styles.button}> - <Text>Click to share message</Text> - </View> - </TouchableHighlight> - <TouchableHighlight style={styles.wrapper} - onPress={this._shareText}> - <View style={styles.button}> - <Text>Click to share message, URL and title</Text> - </View> - </TouchableHighlight> - <Text>{this.state.result}</Text> - </View> - ); - } - - _shareMessage() { - Share.share({ - message: 'React Native | A framework for building native apps using React' - }) - .then(this._showResult) - .catch((error) => this.setState({result: 'error: ' + error.message})); - } - - _shareText() { - Share.share({ - message: 'A framework for building native apps using React', - url: 'http://facebook.github.io/react-native/', - title: 'React Native' - }, { - dialogTitle: 'Share React Native website', - excludedActivityTypes: [ - 'com.apple.UIKit.activity.PostToTwitter' - ], - tintColor: 'green' - }) - .then(this._showResult) - .catch((error) => this.setState({result: 'error: ' + error.message})); - } - - _showResult(result) { - if (result.action === Share.sharedAction) { - if (result.activityType) { - this.setState({result: 'shared with an activityType: ' + result.activityType}); - } else { - this.setState({result: 'shared'}); - } - } else if (result.action === Share.dismissedAction) { - this.setState({result: 'dismissed'}); - } - } - -} - - -var styles = StyleSheet.create({ - wrapper: { - borderRadius: 5, - marginBottom: 5, - }, - button: { - backgroundColor: '#eeeeee', - padding: 10, - }, -});
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/signed-apk-android.html b/docs/signed-apk-android.html index 6a6b3f26e39..5bee14c3849 100644 --- a/docs/signed-apk-android.html +++ b/docs/signed-apk-android.html @@ -1,4 +1,4 @@ -Generating Signed APK

    Generating Signed APK #

    Android requires that all apps be digitally signed with a certificate before they can be installed, so to distribute your Android application via Google Play store, you'll need to generate a signed release APK. The Signing Your Applications page on Android Developers documentation describes the topic in detail. This guide covers the process in brief, as well as lists the steps required to packaging the JavaScript bundle.

    Generating a signing key #

    You can generate a private signing key using keytool. On Windows keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin.

    $ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000

    This command prompts you for passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called my-release-key.keystore.

    The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app, so remember to take note of the alias.

    Note: Remember to keep your keystore file private and never commit it to version control.

    Setting up gradle variables #

    1. Place the my-release-key.keystore file under the android/app directory in your project folder.
    2. Edit the file ~/.gradle/gradle.properties and add the following (replace ***** with the correct keystore password, alias and key password),
    MYAPP_RELEASE_STORE_FILE=my-release-key.keystore +Generating Signed APK

    Generating Signed APK #

    Android requires that all apps be digitally signed with a certificate before they can be installed, so to distribute your Android application via Google Play store, you'll need to generate a signed release APK. The Signing Your Applications page on Android Developers documentation describes the topic in detail. This guide covers the process in brief, as well as lists the steps required to packaging the JavaScript bundle.

    Generating a signing key #

    You can generate a private signing key using keytool. On Windows keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin.

    $ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000

    This command prompts you for passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called my-release-key.keystore.

    The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app, so remember to take note of the alias.

    Note: Remember to keep your keystore file private and never commit it to version control.

    Setting up gradle variables #

    1. Place the my-release-key.keystore file under the android/app directory in your project folder.
    2. Edit the file ~/.gradle/gradle.properties and add the following (replace ***** with the correct keystore password, alias and key password),
    MYAPP_RELEASE_STORE_FILE=my-release-key.keystore MYAPP_RELEASE_KEY_ALIAS=my-key-alias MYAPP_RELEASE_STORE_PASSWORD=***** MYAPP_RELEASE_KEY_PASSWORD=*****

    These are going to be global gradle variables, which we can later use in our gradle config to sign our app.

    Note about saving the keystore:

    Once you publish the app on the Play Store, you will need to republish your app under a different package name (losing all downloads and ratings) if you want to change the signing key at any point. So backup your keystore and don't forget the passwords.

    Note about security: If you are not keen on storing your passwords in plaintext and you are running OSX, you can also store your credentials in the Keychain Access app. Then you can skip the two last rows in ~/.gradle/gradle.properties.

    Adding signing config to your app's gradle config #

    Edit the file android/app/build.gradle in your project folder and add the signing config,

    ... @@ -41,6 +41,6 @@ def enableProguardInReleaseBuilds = \ No newline at end of file + \ No newline at end of file diff --git a/docs/slider.html b/docs/slider.html index ad856a91ec0..aa8a0e67cb9 100644 --- a/docs/slider.html +++ b/docs/slider.html @@ -1,172 +1,18 @@ -Slider

    Slider #

    A component used to select a single value from a range of values.

    Props #

    disabled?: bool #

    If true the user won't be able to move the slider. +Slider

    Slider #

    A component used to select a single value from a range of values.

    Props #

    disabled?: PropTypes.bool #

    If true the user won't be able to move the slider. Default value is false.

    maximumTrackTintColor?: color #

    The color used for the track to the right of the button. -Overrides the default blue gradient image on iOS.

    maximumValue?: number #

    Initial maximum value of the slider. Default value is 1.

    minimumTrackTintColor?: color #

    The color used for the track to the left of the button. -Overrides the default blue gradient image on iOS.

    minimumValue?: number #

    Initial minimum value of the slider. Default value is 0.

    onSlidingComplete?: function #

    Callback called when the user finishes changing the value (e.g. when -the slider is released).

    onValueChange?: function #

    Callback continuously called while the user is dragging the slider.

    step?: number #

    Step value of the slider. The value should be +Overrides the default blue gradient image on iOS.

    maximumValue?: PropTypes.number #

    Initial maximum value of the slider. Default value is 1.

    minimumTrackTintColor?: color #

    The color used for the track to the left of the button. +Overrides the default blue gradient image on iOS.

    minimumValue?: PropTypes.number #

    Initial minimum value of the slider. Default value is 0.

    onSlidingComplete?: PropTypes.func #

    Callback that is called when the user releases the slider, +regardless if the value has changed. The current value is passed +as an argument to the callback handler.

    onValueChange?: PropTypes.func #

    Callback continuously called while the user is dragging the slider.

    step?: PropTypes.number #

    Step value of the slider. The value should be between 0 and (maximumValue - minimumValue). Default value is 0.

    style?: ViewPropTypes.style #

    Used to style and layout the Slider. See StyleSheet.js and -ViewStylePropTypes.js for more info.

    testID?: string #

    Used to locate this view in UI automation tests.

    value?: number #

    Initial value of the slider. The value should be between minimumValue +ViewStylePropTypes.js for more info.

    testID?: PropTypes.string #

    Used to locate this view in UI automation tests.

    value?: PropTypes.number #

    Initial value of the slider. The value should be between minimumValue and maximumValue, which default to 0 and 1 respectively. Default value is 0.

    This is not a controlled component, you don't need to update the value during dragging.

    androidthumbTintColor?: color #

    Color of the foreground switch grip.

    iosmaximumTrackImage?: Image.propTypes.source #

    Assigns a maximum track image. Only static images are supported. The leftmost pixel of the image will be stretched to fill the track.

    iosminimumTrackImage?: Image.propTypes.source #

    Assigns a minimum track image. Only static images are supported. The rightmost pixel of the image will be stretched to fill the track.

    iosthumbImage?: Image.propTypes.source #

    Sets an image for the thumb. Only static images are supported.

    iostrackImage?: Image.propTypes.source #

    Assigns a single image for the track. Only static images are supported. -The center pixel of the image will be stretched to fill the track.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - Slider, - Text, - StyleSheet, - View, -} = ReactNative; - -class SliderExample extends React.Component { - static defaultProps = { - value: 0, - }; - - state = { - value: this.props.value, - }; - - render() { - return ( - <View> - <Text style={styles.text} > - {this.state.value && +this.state.value.toFixed(3)} - </Text> - <Slider - {...this.props} - onValueChange={(value) => this.setState({value: value})} /> - </View> - ); - } -} - -class SlidingCompleteExample extends React.Component { - state = { - slideCompletionValue: 0, - slideCompletionCount: 0, - }; - - render() { - return ( - <View> - <SliderExample - {...this.props} - onSlidingComplete={(value) => this.setState({ - slideCompletionValue: value, - slideCompletionCount: this.state.slideCompletionCount + 1})} /> - <Text> - Completions: {this.state.slideCompletionCount} Value: {this.state.slideCompletionValue} - </Text> - </View> - ); - } -} - -var styles = StyleSheet.create({ - slider: { - height: 10, - margin: 10, - }, - text: { - fontSize: 14, - textAlign: 'center', - fontWeight: '500', - margin: 10, - }, -}); - -exports.title = '<Slider>'; -exports.displayName = 'SliderExample'; -exports.description = 'Slider input for numeric values'; -exports.examples = [ - { - title: 'Default settings', - render(): React.Element<any> { - return <SliderExample />; - } - }, - { - title: 'Initial value: 0.5', - render(): React.Element<any> { - return <SliderExample value={0.5} />; - } - }, - { - title: 'minimumValue: -1, maximumValue: 2', - render(): React.Element<any> { - return ( - <SliderExample - minimumValue={-1} - maximumValue={2} - /> - ); - } - }, - { - title: 'step: 0.25', - render(): React.Element<any> { - return <SliderExample step={0.25} />; - } - }, - { - title: 'onSlidingComplete', - render(): React.Element<any> { - return ( - <SlidingCompleteExample /> - ); - } - }, - { - title: 'Custom min/max track tint color', - render(): React.Element<any> { - return ( - <SliderExample - minimumTrackTintColor={'blue'} - maximumTrackTintColor={'red'} - value={0.5} - /> - ); - } - }, - { - title: 'Custom thumb color', - platform: 'android', - render(): React.Element<any> { - return <SliderExample thumbTintColor={'blue'} />; - } - }, - { - title: 'Custom thumb image', - platform: 'ios', - render(): React.Element<any> { - return <SliderExample thumbImage={require('./uie_thumb_big.png')} />; - } - }, - { - title: 'Custom track image', - platform: 'ios', - render(): React.Element<any> { - return <SliderExample trackImage={require('./slider.png')} />; - } - }, - { - title: 'Custom min/max track image', - platform: 'ios', - render(): React.Element<any> { - return ( - <SliderExample - minimumTrackImage={require('./slider-left.png')} - maximumTrackImage={require('./slider-right.png')} - /> - ); - } - }, -];
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/snapshotviewios.html b/docs/snapshotviewios.html index a8dca6d9302..159dd239996 100644 --- a/docs/snapshotviewios.html +++ b/docs/snapshotviewios.html @@ -1,4 +1,4 @@ -SnapshotViewIOS

    SnapshotViewIOS #

    Props #

    onSnapshotReady?: Function #

    testIdentifier?: string #

    You can edit the content above on GitHub and send us a pull request!

    SnapshotViewIOS #

    Props #

    onSnapshotReady?: Function #

    testIdentifier?: string #

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/state.html b/docs/state.html index e9880909a65..ff90f12767f 100644 --- a/docs/state.html +++ b/docs/state.html @@ -1,4 +1,4 @@ -State

    State #

    There are two types of data that control a component: props and state. props are set by the parent and they are fixed throughout the lifetime of a component. For data that is going to change, we have to use state.

    In general, you should initialize state in the constructor, and then call setState when you want to change it.

    For example, let's say we want to make text that blinks all the time. The text itself gets set once when the blinking component gets created, so the text itself is a prop. The "whether the text is currently on or off" changes over time, so that should be kept in state.

    import React, { Component } from 'react'; +State

    State #

    There are two types of data that control a component: props and state. props are set by the parent and they are fixed throughout the lifetime of a component. For data that is going to change, we have to use state.

    In general, you should initialize state in the constructor, and then call setState when you want to change it.

    For example, let's say we want to make text that blinks all the time. The text itself gets set once when the blinking component gets created, so the text itself is a prop. The "whether the text is currently on or off" changes over time, so that should be kept in state.

    import React, { Component } from 'react'; import { AppRegistry, Text, View } from 'react-native'; class Blink extends Component { @@ -8,7 +8,9 @@ class Blink extends // Toggle the state every second setInterval(() => { - this.setState({ showText: !this.state.showText }); + this.setState(previousState => { + return { showText: !previousState.showText }; + }); }, 1000); } @@ -20,7 +22,7 @@ class Blink extends } } -class BlinkApp extends Component { +export default class BlinkApp extends Component { render() { return ( <View> @@ -32,8 +34,9 @@ class BlinkApp extends ); } } - -AppRegistry.registerComponent('BlinkApp', () => BlinkApp);

    In a real application, you probably won't be setting state with a timer. You might set state when you have new data arrive from the server, or from user input. You can also use a state container like Redux to control your data flow. In that case you would use Redux to modify your state rather than calling setState directly.

    When setState is called, BlinkApp will re-render its Component. By calling setState within the Timer, the component will re-render every time the Timer ticks.

    State works the same way as it does in React, so for more details on handling state, you can look at the React.Component API. + +// skip this line if using Create React Native App +AppRegistry.registerComponent('BlinkApp', () => BlinkApp);

    In a real application, you probably won't be setting state with a timer. You might set state when you have new data arrive from the server, or from user input. You can also use a state container like Redux to control your data flow. In that case you would use Redux to modify your state rather than calling setState directly.

    When setState is called, BlinkApp will re-render its Component. By calling setState within the Timer, the component will re-render every time the Timer ticks.

    State works the same way as it does in React, so for more details on handling state, you can look at the React.Component API. At this point, you might be annoyed that most of our examples so far use boring default black text. To make things more beautiful, you will have to learn about Style.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/statusbar.html b/docs/statusbar.html index 1821ca2168d..99ace788b45 100644 --- a/docs/statusbar.html +++ b/docs/statusbar.html @@ -1,4 +1,4 @@ -StatusBar

    StatusBar #

    Component to control the app status bar.

    Usage with Navigator #

    It is possible to have multiple StatusBar components mounted at the same +StatusBar

    StatusBar #

    Component to control the app status bar.

    Usage with Navigator #

    It is possible to have multiple StatusBar components mounted at the same time. The props will be merged in the order the StatusBar components were mounted. One use case is to specify status bar styles per route using Navigator.

    <View> <StatusBar @@ -23,449 +23,7 @@ Supported for backgroundColor, barStyle and hidden.

    iosnetworkActivityIndicatorVisible?: boolean #

    If the network activity indicator should be visible.

    iosshowHideTransition?: literal | literal #

    The transition effect when showing and hiding the status bar using the hidden prop. Defaults to 'fade'.

    Methods #

    static setHidden(hidden: boolean, animation?: StatusBarAnimation) #

    Show or hide the status bar

    Parameters:
    Name and TypeDescription
    hidden

    boolean

    Hide the status bar.

    [animation]

    Optional animation when - changing the status bar hidden property.

    static setBarStyle(style: StatusBarStyle, animated?: boolean) #

    Set the status bar style

    Parameters:
    Name and TypeDescription
    style

    Status bar style to set

    [animated]

    boolean

    Animate the style change.

    static setNetworkActivityIndicatorVisible(visible: boolean) #

    Control the visibility of the network activity indicator

    Parameters:
    Name and TypeDescription
    visible

    boolean

    Show the indicator.

    static setBackgroundColor(color: string, animated?: boolean) #

    Set the background color for the status bar

    Parameters:
    Name and TypeDescription
    color

    string

    Background color.

    [animated]

    boolean

    Animate the style change.

    static setTranslucent(translucent: boolean) #

    Control the translucency of the status bar

    Parameters:
    Name and TypeDescription
    translucent

    boolean

    Set as translucent.

    Type Definitions #

    StatusBarStyle #

    Status bar style

    Type:
    $Enum

    Constants:
    ValueDescription
    default

    Default status bar style (dark for iOS, light for Android)

    light-content

    Dark background, white texts and icons

    dark-content

    Light background, dark texts and icons

    StatusBarAnimation #

    Status bar animation

    Type:
    $Enum

    Constants:
    ValueDescription
    none

    No animation

    fade

    Fade animation

    slide

    Slide animation

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -const React = require('react'); -const ReactNative = require('react-native'); -const { - StatusBar, - StyleSheet, - Text, - TouchableHighlight, - View, -} = ReactNative; - -exports.framework = 'React'; -exports.title = '<StatusBar>'; -exports.description = 'Component for controlling the status bar'; - -const colors = [ - '#ff0000', - '#00ff00', - '#0000ff', -]; - -const barStyles = [ - 'default', - 'light-content', -]; - -const showHideTransitions = [ - 'fade', - 'slide', -]; - -function getValue<T>(values: Array<T>, index: number): T { - return values[index % values.length]; -} - -class StatusBarHiddenExample extends React.Component { - state = { - animated: true, - hidden: false, - showHideTransition: getValue(showHideTransitions, 0), - }; - - _showHideTransitionIndex = 0; - - _onChangeAnimated = () => { - this.setState({animated: !this.state.animated}); - }; - - _onChangeHidden = () => { - this.setState({hidden: !this.state.hidden}); - }; - - _onChangeTransition = () => { - this._showHideTransitionIndex++; - this.setState({ - showHideTransition: getValue(showHideTransitions, this._showHideTransitionIndex), - }); - }; - - render() { - return ( - <View> - <StatusBar - hidden={this.state.hidden} - showHideTransition={this.state.showHideTransition} - animated={this.state.animated} - /> - <TouchableHighlight - style={styles.wrapper} - onPress={this._onChangeHidden}> - <View style={styles.button}> - <Text>hidden: {this.state.hidden ? 'true' : 'false'}</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={this._onChangeAnimated}> - <View style={styles.button}> - <Text>animated (ios only): {this.state.animated ? 'true' : 'false'}</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={this._onChangeTransition}> - <View style={styles.button}> - <Text> - showHideTransition (ios only): - '{getValue(showHideTransitions, this._showHideTransitionIndex)}' - </Text> - </View> - </TouchableHighlight> - </View> - ); - } -} - -class StatusBarStyleExample extends React.Component { - _barStyleIndex = 0; - - _onChangeBarStyle = () => { - this._barStyleIndex++; - this.setState({barStyle: getValue(barStyles, this._barStyleIndex)}); - }; - - _onChangeAnimated = () => { - this.setState({animated: !this.state.animated}); - }; - - state = { - animated: true, - barStyle: getValue(barStyles, this._barStyleIndex), - }; - - render() { - return ( - <View> - <StatusBar - animated={this.state.animated} - barStyle={this.state.barStyle} - /> - <TouchableHighlight - style={styles.wrapper} - onPress={this._onChangeBarStyle}> - <View style={styles.button}> - <Text>style: '{getValue(barStyles, this._barStyleIndex)}'</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={this._onChangeAnimated}> - <View style={styles.button}> - <Text>animated: {this.state.animated ? 'true' : 'false'}</Text> - </View> - </TouchableHighlight> - </View> - ); - } -} - -class StatusBarNetworkActivityExample extends React.Component { - state = { - networkActivityIndicatorVisible: false, - }; - - _onChangeNetworkIndicatorVisible = () => { - this.setState({ - networkActivityIndicatorVisible: !this.state.networkActivityIndicatorVisible, - }); - }; - - render() { - return ( - <View> - <StatusBar - networkActivityIndicatorVisible={this.state.networkActivityIndicatorVisible} - /> - <TouchableHighlight - style={styles.wrapper} - onPress={this._onChangeNetworkIndicatorVisible}> - <View style={styles.button}> - <Text> - networkActivityIndicatorVisible: - {this.state.networkActivityIndicatorVisible ? 'true' : 'false'} - </Text> - </View> - </TouchableHighlight> - </View> - ); - } -} - -class StatusBarBackgroundColorExample extends React.Component { - state = { - animated: true, - backgroundColor: getValue(colors, 0), - }; - - _colorIndex = 0; - - _onChangeBackgroundColor = () => { - this._colorIndex++; - this.setState({backgroundColor: getValue(colors, this._colorIndex)}); - }; - - _onChangeAnimated = () => { - this.setState({animated: !this.state.animated}); - }; - - render() { - return ( - <View> - <StatusBar - backgroundColor={this.state.backgroundColor} - animated={this.state.animated} - /> - <TouchableHighlight - style={styles.wrapper} - onPress={this._onChangeBackgroundColor}> - <View style={styles.button}> - <Text>backgroundColor: '{getValue(colors, this._colorIndex)}'</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={this._onChangeAnimated}> - <View style={styles.button}> - <Text>animated: {this.state.animated ? 'true' : 'false'}</Text> - </View> - </TouchableHighlight> - </View> - ); - } -} - -class StatusBarTranslucentExample extends React.Component { - state = { - translucent: false, - }; - - _onChangeTranslucent = () => { - this.setState({ - translucent: !this.state.translucent, - }); - }; - - render() { - return ( - <View> - <StatusBar - translucent={this.state.translucent} - /> - <TouchableHighlight - style={styles.wrapper} - onPress={this._onChangeTranslucent}> - <View style={styles.button}> - <Text>translucent: {this.state.translucent ? 'true' : 'false'}</Text> - </View> - </TouchableHighlight> - </View> - ); - } -} - -class StatusBarStaticIOSExample extends React.Component { - render() { - return ( - <View> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setHidden(true, 'slide'); - }}> - <View style={styles.button}> - <Text>setHidden(true, 'slide')</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setHidden(false, 'fade'); - }}> - <View style={styles.button}> - <Text>setHidden(false, 'fade')</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setBarStyle('default', true); - }}> - <View style={styles.button}> - <Text>setBarStyle('default', true)</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setBarStyle('light-content', true); - }}> - <View style={styles.button}> - <Text>setBarStyle('light-content', true)</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setNetworkActivityIndicatorVisible(true); - }}> - <View style={styles.button}> - <Text>setNetworkActivityIndicatorVisible(true)</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setNetworkActivityIndicatorVisible(false); - }}> - <View style={styles.button}> - <Text>setNetworkActivityIndicatorVisible(false)</Text> - </View> - </TouchableHighlight> - </View> - ); - } -} - -class StatusBarStaticAndroidExample extends React.Component { - render() { - return ( - <View> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setHidden(true); - }}> - <View style={styles.button}> - <Text>setHidden(true)</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setHidden(false); - }}> - <View style={styles.button}> - <Text>setHidden(false)</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setBackgroundColor('#ff00ff', true); - }}> - <View style={styles.button}> - <Text>setBackgroundColor('#ff00ff', true)</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setBackgroundColor('#00ff00', true); - }}> - <View style={styles.button}> - <Text>setBackgroundColor('#00ff00', true)</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setTranslucent(true); - StatusBar.setBackgroundColor('rgba(0, 0, 0, 0.4)', true); - }}> - <View style={styles.button}> - <Text>setTranslucent(true) and setBackgroundColor('rgba(0, 0, 0, 0.4)', true)</Text> - </View> - </TouchableHighlight> - <TouchableHighlight - style={styles.wrapper} - onPress={() => { - StatusBar.setTranslucent(false); - StatusBar.setBackgroundColor('black', true); - }}> - <View style={styles.button}> - <Text>setTranslucent(false) and setBackgroundColor('black', true)</Text> - </View> - </TouchableHighlight> - </View> - ); - } -} - -const examples = [{ - title: 'StatusBar hidden', - render() { - return <StatusBarHiddenExample />; - }, -}, { - title: 'StatusBar style', - render() { - return <StatusBarStyleExample />; - }, - platform: 'ios', -}, { - title: 'StatusBar network activity indicator', - render() { - return <StatusBarNetworkActivityExample />; - }, - platform: 'ios', -}, { - title: 'StatusBar background color', - render() { - return <StatusBarBackgroundColorExample />; - }, - platform: 'android', -}, { - title: 'StatusBar background color', - render() { - return <StatusBarTranslucentExample />; - }, - platform: 'android', -}, { - title: 'StatusBar static API', - render() { - return <StatusBarStaticIOSExample />; - }, - platform: 'ios', -}, { - title: 'StatusBar static API', - render() { - return <StatusBarStaticAndroidExample />; - }, - platform: 'android', -}, { - title: 'StatusBar dimensions', - render() { - return ( - <View> - <Text>Height (Android only): {StatusBar.currentHeight} pts</Text> - </View> - ); - }, - platform: 'android', -}]; - -exports.examples = examples; - -var styles = StyleSheet.create({ - wrapper: { - borderRadius: 5, - marginBottom: 5, - }, - button: { - borderRadius: 5, - backgroundColor: '#eeeeee', - padding: 10, - }, - title: { - marginTop: 16, - marginBottom: 8, - fontWeight: 'bold', - } -});
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/statusbarios.html b/docs/statusbarios.html index f10cd3f8056..437041748c3 100644 --- a/docs/statusbarios.html +++ b/docs/statusbarios.html @@ -1,4 +1,4 @@ -StatusBarIOS

    StatusBarIOS #

    Use StatusBar for mutating the status bar.

    You can edit the content above on GitHub and send us a pull request!

    StatusBarIOS #

    Use StatusBar for mutating the status bar.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/style.html b/docs/style.html index 77f25311183..d041b165deb 100644 --- a/docs/style.html +++ b/docs/style.html @@ -1,7 +1,7 @@ -Style

    Style #

    With React Native, you don't use a special language or syntax for defining styles. You just style your application using JavaScript. All of the core components accept a prop named style. The style names and values usually match how CSS works on the web, except names are written using camel casing, e.g backgroundColor rather than background-color.

    The style prop can be a plain old JavaScript object. That's the simplest and what we usually use for example code. You can also pass an array of styles - the last style in the array has precedence, so you can use this to inherit styles.

    As a component grows in complexity, it is often cleaner to use StyleSheet.create to define several styles in one place. Here's an example:

    import React, { Component } from 'react'; +Style

    Style #

    With React Native, you don't use a special language or syntax for defining styles. You just style your application using JavaScript. All of the core components accept a prop named style. The style names and values usually match how CSS works on the web, except names are written using camel casing, e.g backgroundColor rather than background-color.

    The style prop can be a plain old JavaScript object. That's the simplest and what we usually use for example code. You can also pass an array of styles - the last style in the array has precedence, so you can use this to inherit styles.

    As a component grows in complexity, it is often cleaner to use StyleSheet.create to define several styles in one place. Here's an example:

    import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; -class LotsOfStyles extends Component { +export default class LotsOfStyles extends Component { render() { return ( <View> @@ -24,8 +24,9 @@ const styles = StyleSheet: 'red', }, }); - -AppRegistry.registerComponent('LotsOfStyles', () => LotsOfStyles);

    One common pattern is to make your component accept a style prop which in + +// skip this line if using Create React Native App +AppRegistry.registerComponent('LotsOfStyles', () => LotsOfStyles);

    One common pattern is to make your component accept a style prop which in turn is used to style subcomponents. You can use this to make styles "cascade" the way they do in CSS.

    There are a lot more ways to customize text style. Check out the Text component reference for a complete list.

    Now you can make your text beautiful. The next step in becoming a style master is to learn how to control component size.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/stylesheet.html b/docs/stylesheet.html index 095cb8b18b5..95e80c113bd 100644 --- a/docs/stylesheet.html +++ b/docs/stylesheet.html @@ -1,4 +1,4 @@ -StyleSheet

    StyleSheet #

    A StyleSheet is an abstraction similar to CSS StyleSheets

    Create a new StyleSheet:

    var styles = StyleSheet.create({ +StyleSheet

    StyleSheet #

    A StyleSheet is an abstraction similar to CSS StyleSheets

    Create a new StyleSheet:

    var styles = StyleSheet.create({ container: { borderRadius: 4, borderWidth: 0.5, @@ -77,6 +77,6 @@ the alternative use.

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/switch.html b/docs/switch.html index 4f3bbb3114e..479185ed3b0 100644 --- a/docs/switch.html +++ b/docs/switch.html @@ -1,147 +1,10 @@ -Switch

    Switch #

    Renders a boolean input.

    This is a controlled component that requires an onValueChange callback that +Switch

    Switch #

    Renders a boolean input.

    This is a controlled component that requires an onValueChange callback that updates the value prop in order for the component to reflect user actions. If the value prop is not updated, the component will continue to render the supplied value prop instead of the expected result of any user actions.

    @keyword checkbox -@keyword toggle

    Props #

    disabled?: bool #

    If true the user won't be able to toggle the switch. -Default value is false.

    onTintColor?: color #

    Background color when the switch is turned on.

    onValueChange?: function #

    Invoked with the new value when the value changes.

    testID?: string #

    Used to locate this view in end-to-end tests.

    thumbTintColor?: color #

    Color of the foreground switch grip.

    tintColor?: color #

    Border color on iOS and background color on Android when the switch is turned off.

    value?: bool #

    The value of the switch. If true the switch will be turned on. -Default value is false.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - Platform, - Switch, - Text, - View -} = ReactNative; - -class BasicSwitchExample extends React.Component { - state = { - trueSwitchIsOn: true, - falseSwitchIsOn: false, - }; - - render() { - return ( - <View> - <Switch - onValueChange={(value) => this.setState({falseSwitchIsOn: value})} - style={{marginBottom: 10}} - value={this.state.falseSwitchIsOn} /> - <Switch - onValueChange={(value) => this.setState({trueSwitchIsOn: value})} - value={this.state.trueSwitchIsOn} /> - </View> - ); - } -} - -class DisabledSwitchExample extends React.Component { - render() { - return ( - <View> - <Switch - disabled={true} - style={{marginBottom: 10}} - value={true} /> - <Switch - disabled={true} - value={false} /> - </View> - ); - } -} - -class ColorSwitchExample extends React.Component { - state = { - colorTrueSwitchIsOn: true, - colorFalseSwitchIsOn: false, - }; - - render() { - return ( - <View> - <Switch - onValueChange={(value) => this.setState({colorFalseSwitchIsOn: value})} - onTintColor="#00ff00" - style={{marginBottom: 10}} - thumbTintColor="#0000ff" - tintColor="#ff0000" - value={this.state.colorFalseSwitchIsOn} /> - <Switch - onValueChange={(value) => this.setState({colorTrueSwitchIsOn: value})} - onTintColor="#00ff00" - thumbTintColor="#0000ff" - tintColor="#ff0000" - value={this.state.colorTrueSwitchIsOn} /> - </View> - ); - } -} - -class EventSwitchExample extends React.Component { - state = { - eventSwitchIsOn: false, - eventSwitchRegressionIsOn: true, - }; - - render() { - return ( - <View style={{ flexDirection: 'row', justifyContent: 'space-around' }}> - <View> - <Switch - onValueChange={(value) => this.setState({eventSwitchIsOn: value})} - style={{marginBottom: 10}} - value={this.state.eventSwitchIsOn} /> - <Switch - onValueChange={(value) => this.setState({eventSwitchIsOn: value})} - style={{marginBottom: 10}} - value={this.state.eventSwitchIsOn} /> - <Text>{this.state.eventSwitchIsOn ? 'On' : 'Off'}</Text> - </View> - <View> - <Switch - onValueChange={(value) => this.setState({eventSwitchRegressionIsOn: value})} - style={{marginBottom: 10}} - value={this.state.eventSwitchRegressionIsOn} /> - <Switch - onValueChange={(value) => this.setState({eventSwitchRegressionIsOn: value})} - style={{marginBottom: 10}} - value={this.state.eventSwitchRegressionIsOn} /> - <Text>{this.state.eventSwitchRegressionIsOn ? 'On' : 'Off'}</Text> - </View> - </View> - ); - } -} - -var examples = [ - { - title: 'Switches can be set to true or false', - render(): React.Element<any> { return <BasicSwitchExample />; } - }, - { - title: 'Switches can be disabled', - render(): React.Element<any> { return <DisabledSwitchExample />; } - }, - { - title: 'Change events can be detected', - render(): React.Element<any> { return <EventSwitchExample />; } - }, - { - title: 'Switches are controlled components', - render(): React.Element<any> { return <Switch />; } - }, - { - title: 'Custom colors can be provided', - render(): React.Element<any> { return <ColorSwitchExample />; } - } -]; - -exports.title = '<Switch>'; -exports.displayName = 'SwitchExample'; -exports.description = 'Native boolean input'; -exports.examples = examples;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/systrace.html b/docs/systrace.html index 345442cbf2f..0fb868e24df 100644 --- a/docs/systrace.html +++ b/docs/systrace.html @@ -1,4 +1,4 @@ -Systrace

    Systrace #

    Methods #

    static setEnabled(enabled) #

    static beginEvent(profileName?, args?) #

    beginEvent/endEvent for starting and then ending a profile within the same call stack frame

    static endEvent() #

    static beginAsyncEvent(profileName?) #

    beginAsyncEvent/endAsyncEvent for starting and then ending a profile where the end can either +Systrace

    Systrace #

    Methods #

    static setEnabled(enabled) #

    static isEnabled() #

    static beginEvent(profileName?, args?) #

    beginEvent/endEvent for starting and then ending a profile within the same call stack frame

    static endEvent() #

    static beginAsyncEvent(profileName?) #

    beginAsyncEvent/endAsyncEvent for starting and then ending a profile where the end can either occur on another thread or out of the current stack frame, eg await the returned cookie variable should be used as input into the endAsyncEvent call to end the profile

    static endAsyncEvent(profileName?, cookie?) #

    static counterEvent(profileName?, value?) #

    counterEvent registers the value to the profileName on the systrace timeline

    static attachToRelayProfiler(relayProfiler) #

    Relay profiles use await calls, so likely occur out of current stack frame therefore async variant of profiling is used

    static swizzleJSON() #

    This is not called by default due to perf overhead but it's useful @@ -25,6 +25,6 @@ JSON.parse = Systrace.measure('JSON', 'parse', JSON.parse);< apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/tabbarios-item.html b/docs/tabbarios-item.html index 0c7da9626a3..ca89a2077bc 100644 --- a/docs/tabbarios-item.html +++ b/docs/tabbarios-item.html @@ -1,11 +1,27 @@ -TabBarIOS.Item

    TabBarIOS.Item #

    Props #

    badge?: string, number #

    Little red bubble that sits at the top right of the icon.

    badgeColor?: color #

    Background color for the badge. Available since iOS 10.

    icon?: Image.propTypes.source #

    A custom icon for the tab. It is ignored when a system icon is defined.

    onPress?: function #

    Callback when this tab is being selected, you should change the state of your -component to set selected={true}.

    renderAsOriginal?: bool #

    If set to true it renders the image as original, -it defaults to being displayed as a template

    selected?: bool #

    It specifies whether the children are visible or not. If you see a +TabBarIOS.Item

    TabBarIOS.Item #

    Props #

    badge?: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.number, +]) #

    Little red bubble that sits at the top right of the icon.

    badgeColor?: color #

    Background color for the badge. Available since iOS 10.

    icon?: Image.propTypes.source #

    A custom icon for the tab. It is ignored when a system icon is defined.

    onPress?: PropTypes.func #

    Callback when this tab is being selected, you should change the state of your +component to set selected={true}.

    renderAsOriginal?: PropTypes.bool #

    If set to true it renders the image as original, +it defaults to being displayed as a template

    selected?: PropTypes.bool #

    It specifies whether the children are visible or not. If you see a blank content, you probably forgot to add a selected one.

    selectedIcon?: Image.propTypes.source #

    A custom icon when the tab is selected. It is ignored when a system -icon is defined. If left empty, the icon will be tinted in blue.

    style?: ViewPropTypes.style #

    React style object.

    systemIcon?: enum('bookmarks', 'contacts', 'downloads', 'favorites', 'featured', 'history', 'more', 'most-recent', 'most-viewed', 'recents', 'search', 'top-rated') #

    Items comes with a few predefined system icons. Note that if you are +icon is defined. If left empty, the icon will be tinted in blue.

    style?: ViewPropTypes.style #

    React style object.

    systemIcon?: PropTypes.oneOf([ + 'bookmarks', + 'contacts', + 'downloads', + 'favorites', + 'featured', + 'history', + 'more', + 'most-recent', + 'most-viewed', + 'recents', + 'search', + 'top-rated', +]) #

    Items comes with a few predefined system icons. Note that if you are using them, the title and selectedIcon will be overridden with the -system ones.

    title?: string #

    Text that appears under the icon. It is ignored when a system icon -is defined.

    iosisTVSelectable?: bool #

    (Apple TV only)* When set to true, this view will be focusable +system ones.

    title?: PropTypes.string #

    Text that appears under the icon. It is ignored when a system icon +is defined.

    iosisTVSelectable?: PropTypes.bool #

    (Apple TV only)* When set to true, this view will be focusable and navigable using the Apple TV remote.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/tabbarios.html b/docs/tabbarios.html index a53260a5b3e..0325fc21069 100644 --- a/docs/tabbarios.html +++ b/docs/tabbarios.html @@ -1,104 +1,10 @@ -TabBarIOS

    TabBarIOS #

    Props #

    barTintColor?: $FlowFixMe #

    Background color of the tab bar

    itemPositioning?: literal | literal | literal #

    Specifies tab bar item positioning. Available values are: +TabBarIOS

    TabBarIOS #

    Props #

    barTintColor?: $FlowFixMe #

    Background color of the tab bar

    itemPositioning?: literal | literal | literal #

    Specifies tab bar item positioning. Available values are: - fill - distributes items across the entire width of the tab bar - center - centers item in the available tab bar space - auto (default) - distributes items dynamically according to the user interface idiom. In a horizontally compact environment (e.g. iPhone 5) this value defaults to fill, in a horizontally regular one (e.g. iPad) -it defaults to center.

    style?: $FlowFixMe #

    tintColor?: $FlowFixMe #

    Color of the currently selected tab icon

    translucent?: boolean #

    A Boolean value that indicates whether the tab bar is translucent

    unselectedItemTintColor?: $FlowFixMe #

    Color of unselected tab icons. Available since iOS 10.

    unselectedTintColor?: $FlowFixMe #

    Color of text on unselected tabs

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - StyleSheet, - TabBarIOS, - Text, - View, -} = ReactNative; - -var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg=='; - -class TabBarExample extends React.Component { - static title = '<TabBarIOS>'; - static description = 'Tab-based navigation.'; - static displayName = 'TabBarExample'; - - state = { - selectedTab: 'redTab', - notifCount: 0, - presses: 0, - }; - - _renderContent = (color: string, pageText: string, num?: number) => { - return ( - <View style={[styles.tabContent, {backgroundColor: color}]}> - <Text style={styles.tabText}>{pageText}</Text> - <Text style={styles.tabText}>{num} re-renders of the {pageText}</Text> - </View> - ); - }; - - render() { - return ( - <TabBarIOS - unselectedTintColor="yellow" - tintColor="white" - unselectedItemTintColor="red" - barTintColor="darkslateblue"> - <TabBarIOS.Item - title="Blue Tab" - icon={{uri: base64Icon, scale: 3}} - selected={this.state.selectedTab === 'blueTab'} - onPress={() => { - this.setState({ - selectedTab: 'blueTab', - }); - }}> - {this._renderContent('#414A8C', 'Blue Tab')} - </TabBarIOS.Item> - <TabBarIOS.Item - systemIcon="history" - badge={this.state.notifCount > 0 ? this.state.notifCount : undefined} - badgeColor="black" - selected={this.state.selectedTab === 'redTab'} - onPress={() => { - this.setState({ - selectedTab: 'redTab', - notifCount: this.state.notifCount + 1, - }); - }}> - {this._renderContent('#783E33', 'Red Tab', this.state.notifCount)} - </TabBarIOS.Item> - <TabBarIOS.Item - icon={require('./flux.png')} - selectedIcon={require('./relay.png')} - renderAsOriginal - title="More" - selected={this.state.selectedTab === 'greenTab'} - onPress={() => { - this.setState({ - selectedTab: 'greenTab', - presses: this.state.presses + 1 - }); - }}> - {this._renderContent('#21551C', 'Green Tab', this.state.presses)} - </TabBarIOS.Item> - </TabBarIOS> - ); - } -} - -var styles = StyleSheet.create({ - tabContent: { - flex: 1, - alignItems: 'center', - }, - tabText: { - color: 'white', - margin: 50, - }, -}); - -module.exports = TabBarExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/testing.html b/docs/testing.html index 5c4d14173e4..9fca570ab94 100644 --- a/docs/testing.html +++ b/docs/testing.html @@ -1,11 +1,12 @@ -Testing

    Testing #

    This document is about running tests on React Native itself. If you're interested in testing a React Native app, check out the React Native Tutorial on the Jest website.

    Running Tests and Contributing #

    The React Native repo has several tests you can run to verify you haven't caused a regression with your PR. These tests are run with the Travis and CircleCI continuous integration systems, which will automatically annotate pull requests with the test results.

    Whenever you are fixing a bug or adding new functionality to React Native, you should add a test that covers it. Depending on the change you're making, there are different types of tests that may be appropriate.

    JavaScript Tests #

    Jest #

    Jest tests are JavaScript-only tests run on the command line with node. You can run the existing React Native jest tests with:

    $ cd react-native +Testing

    Testing #

    This document is about running tests on React Native itself. If you're interested in testing a React Native app, check out the React Native Tutorial on the Jest website.

    Running Tests and Contributing #

    The React Native repo has several tests you can run to verify you haven't caused a regression with your PR. These tests are run with the Travis and CircleCI continuous integration systems, which will automatically annotate pull requests with the test results.

    Whenever you are fixing a bug or adding new functionality to React Native, you should add a test that covers it. Depending on the change you're making, there are different types of tests that may be appropriate.

    JavaScript Tests #

    Jest #

    Jest tests are JavaScript-only tests run on the command line with node. You can run the existing React Native jest tests with:

    $ cd react-native $ npm test

    It's a good idea to add a Jest test when you are working on a change that only modifies JavaScript code.

    The tests themselves live in the __tests__ directories of the files they test. See TouchableHighlight-test.js for a basic example.

    Flow #

    You should also make sure your code passes Flow tests. These can be run using:

    $ cd react-native $ npm run flow

    Android #

    Unit Tests #

    The Android unit tests do not run in an emulator. They just use a normal Java installation. The default macOS Java install is insufficient, you may need to install Java 8 (JDK8). You can type javac -version in a terminal to see what version you have:

    $ javac -version javac 1.8.0_111

    The version string 1.8.x_xxx corresponds to JDK 8.

    You also need to install the Buck build tool.

    To run the Android unit tests:

    $ cd react-native $ ./scripts/run-android-local-unit-tests.sh

    It's a good idea to add an Android unit test whenever you are working on code that can be tested by Java code alone. The Android unit tests live under ReactAndroid/src/tests, so you can browse through that directory for good examples of tests.

    Integration Tests #

    To run the integration tests, you need to install the Android NDK. See Prerequisites.

    You also need to install the Buck build tool.

    We recommend running the Android integration tests in an emulator, although you can also use a real Android device. It's a good idea to keep the emulator running with a visible window. That way if your tests stall, you can look at the emulator to debug.

    Some devices and some emulator configurations may not work with the tests. We do maintain an emulator configuration that works, as the standard for testing. To run this emulator config:

    $ cd react-native $ ./scripts/run-android-emulator.sh

    Once you have an emulator running, to run the integration tests:

    $ cd react-native -$ ./scripts/run-android-local-integration-tests.sh

    The integration tests should only take a few minutes to run on a modern developer machine.

    It's a good idea to add an Android integration test whenever you are working on code that needs both JavaScript and Java to be tested in conjunction. The Android integration tests live under ReactAndroid/src/androidTest, so you can browse through that directory for good examples of tests.

    iOS #

    Integration Tests #

    React Native provides facilities to make it easier to test integrated components that require both native and JS components to communicate across the bridge. The two main components are RCTTestRunner and RCTTestModule. RCTTestRunner sets up the ReactNative environment and provides facilities to run the tests as XCTestCases in Xcode (runTest:module is the simplest method). RCTTestModule is exported to JS as NativeModules.TestModule.

    The tests themselves are written in JS, and must call TestModule.markTestCompleted() when they are done, otherwise the test will timeout and fail. Test failures are primarily indicated by throwing a JS exception. It is also possible to test error conditions with runTest:module:initialProps:expectErrorRegex: or runTest:module:initialProps:expectErrorBlock: which will expect an error to be thrown and verify the error matches the provided criteria.

    See the following for example usage and integration points:

    You can run integration tests locally with cmd+U in the IntegrationTest and UIExplorer apps in Xcode, or by running the following in the command line on macOS:

    $ cd react-native -$ ./scripts/objc-test-ios.sh test

    Your Xcode install will come with a variety of Simulators running the latest OS. You may need to manually create a new Simulator to match what the XCODE_DESTINATION param in the test script.

    Screenshot/Snapshot Tests #

    A common type of integration test is the snapshot test. These tests render a component, and verify snapshots of the screen against reference images using TestModule.verifySnapshot(), using the FBSnapshotTestCase library behind the scenes. Reference images are recorded by setting recordMode = YES on the RCTTestRunner, then running the tests. Snapshots will differ slightly between 32 and 64 bit, and various OS versions, so it's recommended that you enforce tests are run with the correct configuration. It's also highly recommended that all network data be mocked out, along with other potentially troublesome dependencies. See SimpleSnapshotTest for a basic example.

    If you make a change that affects a snapshot test in a PR, such as adding a new example case to one of the examples that is snapshotted, you'll need to re-record the snapshot reference image. To do this, simply change to _runner.recordMode = YES; in UIExplorer/UIExplorerSnapshotTests.m, re-run the failing tests, then flip record back to NO and submit/update your PR and wait to see if the Travis build passes.

    End-to-end tests #

    Finally, make sure end-to-end tests run successfully by executing the following script:

    $ cd react-native +$ ./scripts/run-android-local-integration-tests.sh

    The integration tests should only take a few minutes to run on a modern developer machine.

    It's a good idea to add an Android integration test whenever you are working on code that needs both JavaScript and Java to be tested in conjunction. The Android integration tests live under ReactAndroid/src/androidTest, so you can browse through that directory for good examples of tests.

    iOS #

    Integration Tests #

    React Native provides facilities to make it easier to test integrated components that require both native and JS components to communicate across the bridge. The two main components are RCTTestRunner and RCTTestModule. RCTTestRunner sets up the ReactNative environment and provides facilities to run the tests as XCTestCases in Xcode (runTest:module is the simplest method). RCTTestModule is exported to JS as NativeModules.TestModule.

    The tests themselves are written in JS, and must call TestModule.markTestCompleted() when they are done, otherwise the test will timeout and fail. Test failures are primarily indicated by throwing a JS exception. It is also possible to test error conditions with runTest:module:initialProps:expectErrorRegex: or runTest:module:initialProps:expectErrorBlock: which will expect an error to be thrown and verify the error matches the provided criteria.

    See the following for example usage and integration points:

    You can run integration tests locally with cmd+U in the IntegrationTest and RNTester apps in Xcode, or by running the following in the command line on macOS:

    $ cd react-native +$ ./scripts/objc-test-ios.sh

    Your Xcode install will come with a variety of Simulators running the latest OS. You may need to manually create a new Simulator to match what the XCODE_DESTINATION param in the test script.

    Screenshot/Snapshot Tests #

    A common type of integration test is the snapshot test. These tests render a component, and verify snapshots of the screen against reference images using TestModule.verifySnapshot(), using the FBSnapshotTestCase library behind the scenes. Reference images are recorded by setting recordMode = YES on the RCTTestRunner, then running the tests. Snapshots will differ slightly between 32 and 64 bit, and various OS versions, so it's recommended that you enforce tests are run with the correct configuration. It's also highly recommended that all network data be mocked out, along with other potentially troublesome dependencies. See SimpleSnapshotTest for a basic example.

    If you make a change that affects a snapshot test in a PR, such as adding a new example case to one of the examples that is snapshotted, you'll need to re-record the snapshot reference image. To do this, simply change to _runner.recordMode = YES; in RNTester/RNTesterSnapshotTests.m, re-run the failing tests, then flip record back to NO and submit/update your PR and wait to see if the Travis build passes.

    Apple TV #

    The same tests discussed above for iOS will also run on tvOS. In the RNTester Xcode project, select the RNTester-tvOS target, and you can follow the same steps above to run the tests in Xcode.

    You can run Apple TV unit and integration tests locally by running the following in the command line on macOS:

    $ cd react-native +$ ./scripts/objc-test-tvos.sh (make sure the line `TEST="test"` is uncommented)

    End-to-end tests #

    Finally, make sure end-to-end tests run successfully by executing the following script:

    $ cd react-native $ ./scripts/test-manual-e2e.sh

    Website #

    The React Native website is hosted on GitHub pages and is automatically generated from Markdown sources as well as comments in the JavaScript source files. It's always a good idea to check that the website is generated properly whenever you edit the docs.

    $ cd website $ npm install $ npm start

    Then open http://localhost:8079/react-native/index.html in your browser.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/text.html b/docs/text.html index e02319fa96f..107d27fb032 100644 --- a/docs/text.html +++ b/docs/text.html @@ -1,9 +1,9 @@ -Text

    Text #

    A React component for displaying text.

    Text supports nesting, styling, and touch handling.

    In the following example, the nested title and body text will inherit the fontFamily from +Text

    Text #

    A React component for displaying text.

    Text supports nesting, styling, and touch handling.

    In the following example, the nested title and body text will inherit the fontFamily from styles.baseText, but the title provides its own additional styles. The title and body will stack on top of each other on account of the literal newlines:

    import React, { Component } from 'react'; import { AppRegistry, Text, StyleSheet } from 'react-native'; -class TextInANest extends Component { +export default class TextInANest extends Component { constructor(props) { super(props); this.state = { @@ -36,32 +36,32 @@ const styles = StyleSheet}, }); -// App registration and rendering -AppRegistry.registerComponent('TextInANest', () => TextInANest);

    Props #

    accessible?: bool #

    When set to true, indicates that the view is an accessibility element. The default value +// skip this line if using Create React Native App +AppRegistry.registerComponent('TextInANest', () => TextInANest);

    Props #

    accessible?: PropTypes.bool #

    When set to true, indicates that the view is an accessibility element. The default value for a Text element is true.

    See the Accessibility guide -for more information.

    allowFontScaling?: bool #

    Specifies whether fonts should scale to respect Text Size accessibility settings. The -default is true.

    ellipsizeMode?: enum('head', 'middle', 'tail', 'clip') #

    When numberOfLines is set, this prop defines how text will be truncated. +for more information.

    allowFontScaling?: PropTypes.bool #

    Specifies whether fonts should scale to respect Text Size accessibility settings. The +default is true.

    ellipsizeMode?: PropTypes.oneOf(['head', 'middle', 'tail', 'clip']) #

    When numberOfLines is set, this prop defines how text will be truncated. numberOfLines must be set in conjunction with this prop.

    This can be one of the following values:

    • head - The line is displayed so that the end fits in the container and the missing text at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz"
    • middle - The line is displayed so that the beginning and end fit in the container and the missing text in the middle is indicated by an ellipsis glyph. "ab...yz"
    • tail - The line is displayed so that the beginning fits in the container and the -missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..."
    • clip - Lines are not drawn past the edge of the text container.

    The default is tail.

    clip is working only for iOS

    numberOfLines?: number #

    Used to truncate the text with an ellipsis after computing the text +missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..."

  • clip - Lines are not drawn past the edge of the text container.
  • The default is tail.

    clip is working only for iOS

    numberOfLines?: PropTypes.number #

    Used to truncate the text with an ellipsis after computing the text layout, including line wrapping, such that the total number of lines -does not exceed this number.

    This prop is commonly used with ellipsizeMode.

    onLayout?: function #

    Invoked on mount and layout changes with

    {nativeEvent: {layout: {x, y, width, height}}}

    onLongPress?: function #

    This function is called on long press.

    e.g., onLongPress={this.increaseSize}>

    onPress?: function #

    This function is called on press.

    e.g., onPress={() => console.log('1st')}

    pressRetentionOffset?: {top: number, left: number, bottom: number, right: number} #

    When the scroll view is disabled, this defines how far your touch may +does not exceed this number.

    This prop is commonly used with ellipsizeMode.

    onLayout?: PropTypes.func #

    Invoked on mount and layout changes with

    {nativeEvent: {layout: {x, y, width, height}}}

    onLongPress?: PropTypes.func #

    This function is called on long press.

    e.g., onLongPress={this.increaseSize}>

    onPress?: PropTypes.func #

    This function is called on press.

    e.g., onPress={() => console.log('1st')}

    pressRetentionOffset?: {top: number, left: number, bottom: number, right: number} #

    When the scroll view is disabled, this defines how far your touch may move off of the button, before deactivating the button. Once deactivated, try moving it back and you'll see that the button is once again reactivated! Move it back and forth several times while the scroll view -is disabled. Ensure you pass in a constant to reduce memory allocations.

    selectable?: bool #

    Lets the user select text, to use the native copy and paste functionality.

    style?: style #

    color color
    fontFamily string
    fontSize number
    fontStyle enum('normal', 'italic')
    fontWeight enum('normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900')

    Specifies font weight. The values 'normal' and 'bold' are supported for +is disabled. Ensure you pass in a constant to reduce memory allocations.

    selectable?: PropTypes.bool #

    Lets the user select text, to use the native copy and paste functionality.

    style?: style #

    color color
    fontFamily string
    fontSize number
    fontStyle enum('normal', 'italic')
    fontWeight enum('normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900')

    Specifies font weight. The values 'normal' and 'bold' are supported for most fonts. Not all fonts have a variant for each of the numeric values, in that case the closest one is chosen.

    lineHeight number
    textAlign enum('auto', 'left', 'right', 'center', 'justify')

    Specifies text alignment. The value 'justify' is only supported on iOS and fallbacks to left on Android.

    textDecorationLine enum('none', 'underline', 'line-through', 'underline line-through')
    textShadowColor color
    textShadowOffset {width: number, height: number}
    textShadowRadius number
    androidincludeFontPadding bool

    Set to false to remove extra font padding intended to make space for certain ascenders / descenders. With some fonts, this padding can make text look slightly misaligned when centered vertically. -For best results also set textAlignVertical to center. Default is true.

    androidtextAlignVertical enum('auto', 'top', 'bottom', 'center')
    iosfontVariant [enum('small-caps', 'oldstyle-nums', 'lining-nums', 'tabular-nums', 'proportional-nums')]
    iosletterSpacing number
    iostextDecorationColor color
    iostextDecorationStyle enum('solid', 'double', 'dotted', 'dashed')
    ioswritingDirection enum('auto', 'ltr', 'rtl')

    testID?: string #

    Used to locate this view in end-to-end tests.

    androidselectionColor?: color #

    The highlight color of the text.

    androidtextBreakStrategy?: enum('simple', 'highQuality', 'balanced') #

    Set text break strategy on Android API Level 23+, possible values are simple, highQuality, balanced -The default value is highQuality.

    iosadjustsFontSizeToFit?: bool #

    Specifies whether font should be scaled down automatically to fit given style constraints.

    iosminimumFontScale?: number #

    Specifies smallest possible scale a font can reach when adjustsFontSizeToFit is enabled. (values 0.01-1.0).

    iossuppressHighlighting?: bool #

    When true, no visual change is made when text is pressed down. By +For best results also set textAlignVertical to center. Default is true.

    androidtextAlignVertical enum('auto', 'top', 'bottom', 'center')
    iosfontVariant [enum('small-caps', 'oldstyle-nums', 'lining-nums', 'tabular-nums', 'proportional-nums')]
    iosletterSpacing number
    iostextDecorationColor color
    iostextDecorationStyle enum('solid', 'double', 'dotted', 'dashed')
    ioswritingDirection enum('auto', 'ltr', 'rtl')

    testID?: PropTypes.string #

    Used to locate this view in end-to-end tests.

    androiddisabled?: PropTypes.bool #

    Specifies the disabled state of the text view for testing purposes

    androidnativeID?: PropTypes.string #

    Used to locate this view from native code.

    androidselectionColor?: color #

    The highlight color of the text.

    androidtextBreakStrategy?: PropTypes.oneOf(['simple', 'highQuality', 'balanced']) #

    Set text break strategy on Android API Level 23+, possible values are simple, highQuality, balanced +The default value is highQuality.

    iosadjustsFontSizeToFit?: PropTypes.bool #

    Specifies whether font should be scaled down automatically to fit given style constraints.

    iosminimumFontScale?: PropTypes.number #

    Specifies smallest possible scale a font can reach when adjustsFontSizeToFit is enabled. (values 0.01-1.0).

    iossuppressHighlighting?: PropTypes.bool #

    When true, no visual change is made when text is pressed down. By default, a gray oval highlights the text on press down.

    You can edit the content above on GitHub and send us a pull request!

    Description #

    Nested Text #

    Both iOS and Android allow you to display formatted text by annotating ranges of a string with specific formatting like bold or colored text (NSAttributedString on iOS, SpannableString on Android). In practice, this is very tedious. For React Native, we decided to use web paradigm for this where you can nest text to achieve the same effect.

    import React, { Component } from 'react'; import { AppRegistry, Text } from 'react-native'; -class BoldAndBeautiful extends Component { +export default class BoldAndBeautiful extends Component { render() { return ( <Text style={{fontWeight: 'bold'}}> @@ -73,13 +73,14 @@ class BoldAndBeautiful extends ); } } - -AppRegistry.registerComponent('BoldAndBeautiful', () => BoldAndBeautiful);

    Behind the scenes, React Native converts this to a flat NSAttributedString or SpannableString that contains the following information:

    "I am bold and red" + +// skip this line if using Create React Native App +AppRegistry.registerComponent('BoldAndBeautiful', () => BoldAndBeautiful);

    Behind the scenes, React Native converts this to a flat NSAttributedString or SpannableString that contains the following information:

    "I am bold and red" 0-9: bold 9-17: bold, red

    Nested Views (iOS Only) #

    On iOS, you can nest views within your Text component. Here's an example:

    import React, { Component } from 'react'; import { AppRegistry, Text, View } from 'react-native'; -class BlueIsCool extends Component { +export default class BlueIsCool extends Component { render() { return ( <Text> @@ -90,8 +91,9 @@ class BlueIsCool extends ); } } - -AppRegistry.registerComponent('BlueIsCool', () => BlueIsCool);

    In order to use this feature, you must give the view a width and a height.

    Containers #

    The <Text> element is special relative to layout: everything inside is no longer using the flexbox layout but using text layout. This means that elements inside of a <Text> are no longer rectangles, but wrap when they see the end of the line.

    <Text> + +// skip this line if using Create React Native App +AppRegistry.registerComponent('BlueIsCool', () => BlueIsCool);

    In order to use this feature, you must give the view a width and a height.

    Containers #

    The <Text> element is special relative to layout: everything inside is no longer using the flexbox layout but using text layout. This means that elements inside of a <Text> are no longer rectangles, but wrap when they see the end of the line.

    <Text> <Text>First part and </Text> <Text>second part</Text> </Text> @@ -138,1010 +140,7 @@ html { <Text style={{color: 'red'}}> and red </Text> -</Text>

    We believe that this more constrained way to style text will yield better apps:

    • (Developer) React components are designed with strong isolation in mind: You should be able to drop a component anywhere in your application, trusting that as long as the props are the same, it will look and behave the same way. Text properties that could inherit from outside of the props would break this isolation.

    • (Implementor) The implementation of React Native is also simplified. We do not need to have a fontFamily field on every single element, and we do not need to potentially traverse the tree up to the root every time we display a text node. The style inheritance is only encoded inside of the native Text component and doesn't leak to other components or the system itself.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    IOS #

    Edit on GitHub
    'use strict'; - -const Platform = require('Platform'); -var React = require('react'); -var ReactNative = require('react-native'); -var { - Image, - StyleSheet, - Text, - View, - LayoutAnimation, -} = ReactNative; - -class Entity extends React.Component { - render() { - return ( - <Text style={{fontWeight: '500', color: '#527fe4'}}> - {this.props.children} - </Text> - ); - } -} - -class AttributeToggler extends React.Component { - state = {fontWeight: 'bold', fontSize: 15}; - - toggleWeight = () => { - this.setState({ - fontWeight: this.state.fontWeight === 'bold' ? 'normal' : 'bold' - }); - }; - - increaseSize = () => { - this.setState({ - fontSize: this.state.fontSize + 1 - }); - }; - - render() { - var curStyle = {fontWeight: this.state.fontWeight, fontSize: this.state.fontSize}; - return ( - <View> - <Text style={curStyle}> - Tap the controls below to change attributes. - </Text> - <Text> - <Text>See how it will even work on <Text style={curStyle}>this nested text</Text></Text> - </Text> - <Text - style={{backgroundColor: '#ffaaaa', marginTop: 5}} - onPress={this.toggleWeight}> - Toggle Weight - </Text> - <Text - style={{backgroundColor: '#aaaaff', marginTop: 5}} - onPress={this.increaseSize}> - Increase Size - </Text> - </View> - ); - } -} - -var AdjustingFontSize = React.createClass({ - getInitialState: function() { - return {dynamicText:'', shouldRender: true,}; - }, - reset: function() { - LayoutAnimation.easeInEaseOut(); - this.setState({ - shouldRender: false, - }); - setTimeout(()=>{ - LayoutAnimation.easeInEaseOut(); - this.setState({ - dynamicText: '', - shouldRender: true, - }); - }, 300); - }, - addText: function() { - this.setState({ - dynamicText: this.state.dynamicText + (Math.floor((Math.random() * 10) % 2) ? ' foo' : ' bar'), - }); - }, - removeText: function() { - this.setState({ - dynamicText: this.state.dynamicText.slice(0, this.state.dynamicText.length - 4), - }); - }, - render: function() { - - if (!this.state.shouldRender) { - return (<View/>); - } - return ( - <View> - <Text lineBreakMode="tail" numberOfLines={1} style={{fontSize: 36, marginVertical:6}}> - Truncated text is baaaaad. - </Text> - <Text numberOfLines={1} adjustsFontSizeToFit={true} style={{fontSize: 40, marginVertical:6}}> - Shrinking to fit available space is much better! - </Text> - - <Text adjustsFontSizeToFit={true} numberOfLines={1} style={{fontSize:30, marginVertical:6}}> - {'Add text to me to watch me shrink!' + ' ' + this.state.dynamicText} - </Text> - - <Text adjustsFontSizeToFit={true} numberOfLines={4} style={{fontSize:20, marginVertical:6}}> - {'Multiline text component shrinking is supported, watch as this reeeeaaaally loooooong teeeeeeext grooooows and then shriiiinks as you add text to me! ioahsdia soady auydoa aoisyd aosdy ' + ' ' + this.state.dynamicText} - </Text> - - <Text adjustsFontSizeToFit={true} numberOfLines={1} style={{marginVertical:6}}> - <Text style={{fontSize:14}}> - {'Differently sized nested elements will shrink together. '} - </Text> - <Text style={{fontSize:20}}> - {'LARGE TEXT! ' + this.state.dynamicText} - </Text> - </Text> - - <View style={{flexDirection:'row', justifyContent:'space-around', marginTop: 5, marginVertical:6}}> - <Text - style={{backgroundColor: '#ffaaaa'}} - onPress={this.reset}> - Reset - </Text> - <Text - style={{backgroundColor: '#aaaaff'}} - onPress={this.removeText}> - Remove Text - </Text> - <Text - style={{backgroundColor: '#aaffaa'}} - onPress={this.addText}> - Add Text - </Text> - </View> - </View> - ); - } -}); - -exports.title = '<Text>'; -exports.description = 'Base component for rendering styled text.'; -exports.displayName = 'TextExample'; -exports.examples = [ -{ - title: 'Wrap', - render: function() { - return ( - <Text> - The text should wrap if it goes on multiple lines. See, this is going to - the next line. - </Text> - ); - }, -}, { - title: 'Padding', - render: function() { - return ( - <Text style={{padding: 10}}> - This text is indented by 10px padding on all sides. - </Text> - ); - }, -}, { - title: 'Font Family', - render: function() { - return ( - <View> - <Text style={{fontFamily: (Platform.isTVOS ? 'Times' : 'Cochin')}}> - Cochin - </Text> - <Text style={{fontFamily: (Platform.isTVOS ? 'Times' : 'Cochin'), fontWeight: 'bold'}}> - Cochin bold - </Text> - <Text style={{fontFamily: 'Helvetica'}}> - Helvetica - </Text> - <Text style={{fontFamily: 'Helvetica', fontWeight: 'bold'}}> - Helvetica bold - </Text> - <Text style={{fontFamily: (Platform.isTVOS ? 'Courier' : 'Verdana')}}> - Verdana - </Text> - <Text style={{fontFamily: (Platform.isTVOS ? 'Courier' : 'Verdana'), fontWeight: 'bold'}}> - Verdana bold - </Text> - </View> - ); - }, -}, { - title: 'Font Size', - render: function() { - return ( - <View> - <Text style={{fontSize: 23}}> - Size 23 - </Text> - <Text style={{fontSize: 8}}> - Size 8 - </Text> - </View> - ); - }, -}, { - title: 'Color', - render: function() { - return ( - <View> - <Text style={{color: 'red'}}> - Red color - </Text> - <Text style={{color: 'blue'}}> - Blue color - </Text> - </View> - ); - }, -}, { - title: 'Font Weight', - render: function() { - return ( - <View> - <Text style={{fontSize: 20, fontWeight: '100'}}> - Move fast and be ultralight - </Text> - <Text style={{fontSize: 20, fontWeight: '200'}}> - Move fast and be light - </Text> - <Text style={{fontSize: 20, fontWeight: 'normal'}}> - Move fast and be normal - </Text> - <Text style={{fontSize: 20, fontWeight: 'bold'}}> - Move fast and be bold - </Text> - <Text style={{fontSize: 20, fontWeight: '900'}}> - Move fast and be ultrabold - </Text> - </View> - ); - }, -}, { - title: 'Font Style', - render: function() { - return ( - <View> - <Text style={{fontStyle: 'normal'}}> - Normal text - </Text> - <Text style={{fontStyle: 'italic'}}> - Italic text - </Text> - </View> - ); - }, -}, { - title: 'Selectable', - render: function() { - return ( - <View> - <Text selectable={true}> - This text is <Text style={{fontWeight: 'bold'}}>selectable</Text> if you click-and-hold. - </Text> - </View> - ); - }, -}, { - title: 'Text Decoration', - render: function() { - return ( - <View> - <Text style={{textDecorationLine: 'underline', textDecorationStyle: 'solid'}}> - Solid underline - </Text> - <Text style={{textDecorationLine: 'underline', textDecorationStyle: 'double', textDecorationColor: '#ff0000'}}> - Double underline with custom color - </Text> - <Text style={{textDecorationLine: 'underline', textDecorationStyle: 'dashed', textDecorationColor: '#9CDC40'}}> - Dashed underline with custom color - </Text> - <Text style={{textDecorationLine: 'underline', textDecorationStyle: 'dotted', textDecorationColor: 'blue'}}> - Dotted underline with custom color - </Text> - <Text style={{textDecorationLine: 'none'}}> - None textDecoration - </Text> - <Text style={{textDecorationLine: 'line-through', textDecorationStyle: 'solid'}}> - Solid line-through - </Text> - <Text style={{textDecorationLine: 'line-through', textDecorationStyle: 'double', textDecorationColor: '#ff0000'}}> - Double line-through with custom color - </Text> - <Text style={{textDecorationLine: 'line-through', textDecorationStyle: 'dashed', textDecorationColor: '#9CDC40'}}> - Dashed line-through with custom color - </Text> - <Text style={{textDecorationLine: 'line-through', textDecorationStyle: 'dotted', textDecorationColor: 'blue'}}> - Dotted line-through with custom color - </Text> - <Text style={{textDecorationLine: 'underline line-through'}}> - Both underline and line-through - </Text> - </View> - ); - }, -}, { - title: 'Nested', - description: 'Nested text components will inherit the styles of their ' + - 'parents (only backgroundColor is inherited from non-Text parents). ' + - '<Text> only supports other <Text> and raw text (strings) as children.', - render: function() { - return ( - <View> - <Text> - (Normal text, - <Text style={{fontWeight: 'bold'}}> - (and bold - <Text style={{fontSize: 11, color: '#527fe4'}}> - (and tiny inherited bold blue) - </Text> - ) - </Text> - ) - </Text> - <Text style={{opacity:0.7}}> - (opacity - <Text> - (is inherited - <Text style={{opacity:0.7}}> - (and accumulated - <Text style={{backgroundColor:'#ffaaaa'}}> - (and also applies to the background) - </Text> - ) - </Text> - ) - </Text> - ) - </Text> - <Text style={{fontSize: 12}}> - <Entity>Entity Name</Entity> - </Text> - </View> - ); - }, -}, { - title: 'Text Align', - render: function() { - return ( - <View> - <Text> - auto (default) - english LTR - </Text> - <Text> - أحب اللغة العربية auto (default) - arabic RTL - </Text> - <Text style={{textAlign: 'left'}}> - left left left left left left left left left left left left left left left - </Text> - <Text style={{textAlign: 'center'}}> - center center center center center center center center center center center - </Text> - <Text style={{textAlign: 'right'}}> - right right right right right right right right right right right right right - </Text> - <Text style={{textAlign: 'justify'}}> - justify: this text component{"'"}s contents are laid out with "textAlign: justify" - and as you can see all of the lines except the last one span the - available width of the parent container. - </Text> - </View> - ); - }, -}, { - title: 'Letter Spacing', - render: function() { - return ( - <View> - <Text style={{letterSpacing: 0}}> - letterSpacing = 0 - </Text> - <Text style={{letterSpacing: 2, marginTop: 5}}> - letterSpacing = 2 - </Text> - <Text style={{letterSpacing: 9, marginTop: 5}}> - letterSpacing = 9 - </Text> - <Text style={{letterSpacing: -1, marginTop: 5}}> - letterSpacing = -1 - </Text> - </View> - ); - }, -}, { - title: 'Spaces', - render: function() { - return ( - <Text> - A {'generated'} {' '} {'string'} and some &nbsp;&nbsp;&nbsp; spaces - </Text> - ); - }, -}, { - title: 'Line Height', - render: function() { - return ( - <Text> - <Text style={{lineHeight: 35}}> - A lot of space between the lines of this long passage that should - wrap once. - </Text> - </Text> - ); - }, -}, { - title: 'Empty Text', - description: 'It\'s ok to have Text with zero or null children.', - render: function() { - return ( - <Text /> - ); - }, -}, { - title: 'Toggling Attributes', - render: function(): React.Element<any> { - return <AttributeToggler />; - }, -}, { - title: 'backgroundColor attribute', - description: 'backgroundColor is inherited from all types of views.', - render: function() { - return ( - <Text style={{backgroundColor: 'yellow'}}> - Yellow container background, - <Text style={{backgroundColor: '#ffaaaa'}}> - {' '}red background, - <Text style={{backgroundColor: '#aaaaff'}}> - {' '}blue background, - <Text> - {' '}inherited blue background, - <Text style={{backgroundColor: '#aaffaa'}}> - {' '}nested green background. - </Text> - </Text> - </Text> - </Text> - </Text> - ); - }, -}, { - title: 'numberOfLines attribute', - render: function() { - return ( - <View> - <Text numberOfLines={1}> - Maximum of one line, no matter how much I write here. If I keep writing, it{"'"}ll just truncate after one line. - </Text> - <Text numberOfLines={2} style={{marginTop: 20}}> - Maximum of two lines, no matter how much I write here. If I keep writing, it{"'"}ll just truncate after two lines. - </Text> - <Text style={{marginTop: 20}}> - No maximum lines specified, no matter how much I write here. If I keep writing, it{"'"}ll just keep going and going. - </Text> - </View> - ); - }, -}, { - title: 'Text highlighting (tap the link to see highlight)', - render: function() { - return ( - <View> - <Text>Lorem ipsum dolor sit amet, <Text suppressHighlighting={false} style={{backgroundColor: 'white', textDecorationLine: 'underline', color: 'blue'}} onPress={() => null}>consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud</Text> exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</Text> - </View> - ); - }, -}, { - title: 'allowFontScaling attribute', - render: function() { - return ( - <View> - <Text> - By default, text will respect Text Size accessibility setting on iOS. - It means that all font sizes will be increased or descreased depending on the value of Text Size setting in - {" "}<Text style={{fontWeight: 'bold'}}>Settings.app - Display & Brightness - Text Size</Text> - </Text> - <Text style={{marginTop: 10}}> - You can disable scaling for your Text component by passing {"\""}allowFontScaling={"{"}false{"}\""} prop. - </Text> - <Text allowFontScaling={false} style={{marginTop: 20}}> - This text will not scale. - </Text> - </View> - ); - }, -}, { - title: 'Inline views', - render: function() { - return ( - <View> - <Text> - This text contains an inline blue view <View style={{width: 25, height: 25, backgroundColor: 'steelblue'}} /> and - an inline image <Image source={require('./flux.png')} style={{width: 30, height: 11, resizeMode: 'cover'}}/>. Neat, huh? - </Text> - </View> - ); - }, -}, { - title: 'Text shadow', - render: function() { - return ( - <View> - <Text style={{fontSize: 20, textShadowOffset: {width: 2, height: 2}, textShadowRadius: 1, textShadowColor: '#00cccc'}}> - Demo text shadow - </Text> - </View> - ); - }, -}, { - title: 'Ellipsize mode', - render: function() { - return ( - <View> - <Text numberOfLines={1}> - This very long text should be truncated with dots in the end. - </Text> - <Text ellipsizeMode="middle" numberOfLines={1}> - This very long text should be truncated with dots in the middle. - </Text> - <Text ellipsizeMode="head" numberOfLines={1}> - This very long text should be truncated with dots in the beginning. - </Text> - <Text ellipsizeMode="clip" numberOfLines={1}> - This very looooooooooooooooooooooooooooong text should be clipped. - </Text> - </View> - ); - }, -}, { - title: 'Font variants', - render: function() { - return ( - <View> - <Text style={{fontVariant: ['small-caps']}}> - Small Caps{'\n'} - </Text> - <Text style={{fontFamily: (Platform.isTVOS ? 'Times' : 'Hoefler Text'), fontVariant: ['oldstyle-nums']}}> - Old Style nums 0123456789{'\n'} - </Text> - <Text style={{fontFamily: (Platform.isTVOS ? 'Times' : 'Hoefler Text'), fontVariant: ['lining-nums']}}> - Lining nums 0123456789{'\n'} - </Text> - <Text style={{fontVariant: ['tabular-nums']}}> - Tabular nums{'\n'} - 1111{'\n'} - 2222{'\n'} - </Text> - <Text style={{fontVariant: ['proportional-nums']}}> - Proportional nums{'\n'} - 1111{'\n'} - 2222{'\n'} - </Text> - </View> - ); - }, -}, { - title: 'Dynamic Font Size Adjustment', - render: function(): React.Element<any> { - return <AdjustingFontSize />; - }, -}];

    ANDROID #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - Image, - StyleSheet, - Text, - View, -} = ReactNative; -var UIExplorerBlock = require('./UIExplorerBlock'); -var UIExplorerPage = require('./UIExplorerPage'); - -class Entity extends React.Component { - render() { - return ( - <Text style={{fontWeight: 'bold', color: '#527fe4'}}> - {this.props.children} - </Text> - ); - } -} - -class AttributeToggler extends React.Component { - state = {fontWeight: 'bold', fontSize: 15}; - - toggleWeight = () => { - this.setState({ - fontWeight: this.state.fontWeight === 'bold' ? 'normal' : 'bold' - }); - }; - - increaseSize = () => { - this.setState({ - fontSize: this.state.fontSize + 1 - }); - }; - - render() { - var curStyle = {fontWeight: this.state.fontWeight, fontSize: this.state.fontSize}; - return ( - <View> - <Text style={curStyle}> - Tap the controls below to change attributes. - </Text> - <Text> - <Text>See how it will even work on <Text style={curStyle}>this nested text</Text></Text> - </Text> - <Text> - <Text onPress={this.toggleWeight}>Toggle Weight</Text> - {' (with highlight onPress)'} - </Text> - <Text onPress={this.increaseSize} suppressHighlighting={true}> - Increase Size (suppressHighlighting true) - </Text> - </View> - ); - } -} - -class TextExample extends React.Component { - static title = '<Text>'; - static description = 'Base component for rendering styled text.'; - - render() { - return ( - <UIExplorerPage title="<Text>"> - <UIExplorerBlock title="Wrap"> - <Text> - The text should wrap if it goes on multiple lines. - See, this is going to the next line. - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Padding"> - <Text style={{padding: 10}}> - This text is indented by 10px padding on all sides. - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Font Family"> - <Text style={{fontFamily: 'sans-serif'}}> - Sans-Serif - </Text> - <Text style={{fontFamily: 'sans-serif', fontWeight: 'bold'}}> - Sans-Serif Bold - </Text> - <Text style={{fontFamily: 'serif'}}> - Serif - </Text> - <Text style={{fontFamily: 'serif', fontWeight: 'bold'}}> - Serif Bold - </Text> - <Text style={{fontFamily: 'monospace'}}> - Monospace - </Text> - <Text style={{fontFamily: 'monospace', fontWeight: 'bold'}}> - Monospace Bold (After 5.0) - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Android Material Design fonts"> - <View style={{flexDirection: 'row', alignItems: 'flex-start'}}> - <View style={{flex: 1}}> - <Text style={{fontFamily: 'sans-serif'}}> - Roboto Regular - </Text> - <Text style={{fontFamily: 'sans-serif', fontStyle: 'italic'}}> - Roboto Italic - </Text> - <Text style={{fontFamily: 'sans-serif', fontWeight: 'bold'}}> - Roboto Bold - </Text> - <Text style={{fontFamily: 'sans-serif', fontStyle: 'italic', fontWeight: 'bold'}}> - Roboto Bold Italic - </Text> - <Text style={{fontFamily: 'sans-serif-light'}}> - Roboto Light - </Text> - <Text style={{fontFamily: 'sans-serif-light', fontStyle: 'italic'}}> - Roboto Light Italic - </Text> - <Text style={{fontFamily: 'sans-serif-thin'}}> - Roboto Thin (After 4.2) - </Text> - <Text style={{fontFamily: 'sans-serif-thin', fontStyle: 'italic'}}> - Roboto Thin Italic (After 4.2) - </Text> - <Text style={{fontFamily: 'sans-serif-condensed'}}> - Roboto Condensed - </Text> - <Text style={{fontFamily: 'sans-serif-condensed', fontStyle: 'italic'}}> - Roboto Condensed Italic - </Text> - <Text style={{fontFamily: 'sans-serif-condensed', fontWeight: 'bold'}}> - Roboto Condensed Bold - </Text> - <Text style={{ - fontFamily: 'sans-serif-condensed', - fontStyle: 'italic', - fontWeight: 'bold'}}> - Roboto Condensed Bold Italic - </Text> - <Text style={{fontFamily: 'sans-serif-medium'}}> - Roboto Medium (After 5.0) - </Text> - <Text style={{fontFamily: 'sans-serif-medium', fontStyle: 'italic'}}> - Roboto Medium Italic (After 5.0) - </Text> - </View> - </View> - </UIExplorerBlock> - <UIExplorerBlock title="Custom Fonts"> - <View style={{flexDirection: 'row', alignItems: 'flex-start'}}> - <View style={{flex: 1}}> - <Text style={{fontFamily: 'notoserif'}}> - NotoSerif Regular - </Text> - <Text style={{fontFamily: 'notoserif', fontStyle: 'italic', fontWeight: 'bold'}}> - NotoSerif Bold Italic - </Text> - <Text style={{fontFamily: 'notoserif', fontStyle: 'italic'}}> - NotoSerif Italic (Missing Font file) - </Text> - </View> - </View> - </UIExplorerBlock> - - <UIExplorerBlock title="Font Size"> - <Text style={{fontSize: 23}}> - Size 23 - </Text> - <Text style={{fontSize: 8}}> - Size 8 - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Color"> - <Text style={{color: 'red'}}> - Red color - </Text> - <Text style={{color: 'blue'}}> - Blue color - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Font Weight"> - <Text style={{fontWeight: 'bold'}}> - Move fast and be bold - </Text> - <Text style={{fontWeight: 'normal'}}> - Move fast and be bold - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Font Style"> - <Text style={{fontStyle: 'italic'}}> - Move fast and be bold - </Text> - <Text style={{fontStyle: 'normal'}}> - Move fast and be bold - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Font Style and Weight"> - <Text style={{fontStyle: 'italic', fontWeight: 'bold'}}> - Move fast and be bold - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Text Decoration"> - <Text style={{textDecorationLine: 'underline'}}> - Solid underline - </Text> - <Text style={{textDecorationLine: 'none'}}> - None textDecoration - </Text> - <Text style={{textDecorationLine: 'line-through', textDecorationStyle: 'solid'}}> - Solid line-through - </Text> - <Text style={{textDecorationLine: 'underline line-through'}}> - Both underline and line-through - </Text> - <Text> - Mixed text with <Text style={{textDecorationLine: 'underline'}}>underline</Text> and <Text style={{textDecorationLine: 'line-through'}}>line-through</Text> text nodes - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Nested"> - <Text onPress={() => console.log('1st')}> - (Normal text, - <Text style={{fontWeight: 'bold'}} onPress={() => console.log('2nd')}> - (and bold - <Text style={{fontStyle: 'italic', fontSize: 11, color: '#527fe4'}} onPress={() => console.log('3rd')}> - (and tiny bold italic blue - <Text style={{fontWeight: 'normal', fontStyle: 'normal'}} onPress={() => console.log('4th')}> - (and tiny normal blue) - </Text> - ) - </Text> - ) - </Text> - ) - </Text> - <Text style={{fontFamily: 'serif'}} onPress={() => console.log('1st')}> - (Serif - <Text style={{fontStyle: 'italic', fontWeight: 'bold'}} onPress={() => console.log('2nd')}> - (Serif Bold Italic - <Text - style={{fontFamily: 'monospace', fontStyle: 'normal', fontWeight: 'normal'}} - onPress={() => console.log('3rd')}> - (Monospace Normal - <Text - style={{fontFamily: 'sans-serif', fontWeight: 'bold'}} - onPress={() => console.log('4th')}> - (Sans-Serif Bold - <Text style={{fontWeight: 'normal'}} onPress={() => console.log('5th')}> - (and Sans-Serif Normal) - </Text> - ) - </Text> - ) - </Text> - ) - </Text> - ) - </Text> - <Text style={{fontSize: 12}}> - <Entity>Entity Name</Entity> - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Text Align"> - <Text> - auto (default) - english LTR - </Text> - <Text> - أحب اللغة العربية auto (default) - arabic RTL - </Text> - <Text style={{textAlign: 'left'}}> - left left left left left left left left left left left left left left left - </Text> - <Text style={{textAlign: 'center'}}> - center center center center center center center center center center center - </Text> - <Text style={{textAlign: 'right'}}> - right right right right right right right right right right right right right - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Unicode"> - <View> - <View style={{flexDirection: 'row'}}> - <Text style={{backgroundColor: 'red'}}> - 星际争霸是世界上最好的游戏。 - </Text> - </View> - <View> - <Text style={{backgroundColor: 'red'}}> - 星际争霸是世界上最好的游戏。 - </Text> - </View> - <View style={{alignItems: 'center'}}> - <Text style={{backgroundColor: 'red'}}> - 星际争霸是世界上最好的游戏。 - </Text> - </View> - <View> - <Text style={{backgroundColor: 'red'}}> - 星际争霸是世界上最好的游戏。星际争霸是世界上最好的游戏。星际争霸是世界上最好的游戏。星际争霸是世界上最好的游戏。 - </Text> - </View> - </View> - </UIExplorerBlock> - <UIExplorerBlock title="Spaces"> - <Text> - A {'generated'} {' '} {'string'} and some &nbsp;&nbsp;&nbsp; spaces - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Line Height"> - <Text style={{lineHeight: 35}}> - Holisticly formulate inexpensive ideas before best-of-breed benefits. <Text style={{fontSize: 20}}>Continually</Text> expedite magnetic potentialities rather than client-focused interfaces. - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Empty Text"> - <Text /> - </UIExplorerBlock> - <UIExplorerBlock title="Toggling Attributes"> - <AttributeToggler /> - </UIExplorerBlock> - <UIExplorerBlock title="backgroundColor attribute"> - <Text style={{backgroundColor: '#ffaaaa'}}> - Red background, - <Text style={{backgroundColor: '#aaaaff'}}> - {' '}blue background, - <Text> - {' '}inherited blue background, - <Text style={{backgroundColor: '#aaffaa'}}> - {' '}nested green background. - </Text> - </Text> - </Text> - </Text> - <Text style={{backgroundColor: 'rgba(100, 100, 100, 0.3)'}}> - Same alpha as background, - <Text> - Inherited alpha from background, - <Text style={{backgroundColor: 'rgba(100, 100, 100, 0.3)'}}> - Reapply alpha - </Text> - </Text> - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="containerBackgroundColor attribute"> - <View style={{flexDirection: 'row', height: 85}}> - <View style={{backgroundColor: '#ffaaaa', width: 150}} /> - <View style={{backgroundColor: '#aaaaff', width: 150}} /> - </View> - <Text style={[styles.backgroundColorText, {top: -80}]}> - Default containerBackgroundColor (inherited) + backgroundColor wash - </Text> - <Text style={[styles.backgroundColorText, {top: -70, backgroundColor: 'transparent'}]}> - {"containerBackgroundColor: 'transparent' + backgroundColor wash"} - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="numberOfLines attribute"> - <Text numberOfLines={1}> - Maximum of one line no matter now much I write here. If I keep writing it{"'"}ll just truncate after one line - </Text> - <Text numberOfLines={2} style={{marginTop: 20}}> - Maximum of two lines no matter now much I write here. If I keep writing it{"'"}ll just truncate after two lines - </Text> - <Text style={{marginTop: 20}}> - No maximum lines specified no matter now much I write here. If I keep writing it{"'"}ll just keep going and going - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="selectable attribute"> - <Text selectable> - This text is selectable if you click-and-hold, and will offer the native Android selection menus. - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="selectionColor attribute"> - <Text selectable selectionColor="orange"> - This text will have a orange highlight on selection. - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Inline images"> - <Text> - This text contains an inline image <Image source={require('./flux.png')}/>. Neat, huh? - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Text shadow"> - <Text style={{fontSize: 20, textShadowOffset: {width: 2, height: 2}, textShadowRadius: 1, textShadowColor: '#00cccc'}}> - Demo text shadow - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Ellipsize mode"> - <Text numberOfLines={1}> - This very long text should be truncated with dots in the end. - </Text> - <Text ellipsizeMode="middle" numberOfLines={1}> - This very long text should be truncated with dots in the middle. - </Text> - <Text ellipsizeMode="head" numberOfLines={1}> - This very long text should be truncated with dots in the beginning. - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Include Font Padding"> - <View style={{flexDirection: 'row', justifyContent: 'space-around', marginBottom: 10}}> - <View style={{alignItems: 'center'}}> - <Text style={styles.includeFontPaddingText}> - Ey - </Text> - <Text>Default</Text> - </View> - <View style={{alignItems: 'center'}}> - <Text style={[styles.includeFontPaddingText, {includeFontPadding: false, marginLeft: 10}]}> - Ey - </Text> - <Text>includeFontPadding: false</Text> - </View> - </View> - <Text>By default Android will put extra space above text to allow for upper-case accents or other ascenders. With some fonts, this can make text look slightly misaligned when centered vertically.</Text> - </UIExplorerBlock> - </UIExplorerPage> - ); - } -} - -var styles = StyleSheet.create({ - backgroundColorText: { - left: 5, - backgroundColor: 'rgba(100, 100, 100, 0.3)' - }, - includeFontPaddingText: { - fontSize: 120, - fontFamily: 'sans-serif', - backgroundColor: '#EEEEEE', - color: '#000000', - textAlignVertical: 'center', - alignSelf: 'center', - } -}); - -module.exports = TextExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/textinput.html b/docs/textinput.html index b0767145610..39214c07053 100644 --- a/docs/textinput.html +++ b/docs/textinput.html @@ -1,4 +1,4 @@ -TextInput

    TextInput #

    A foundational component for inputting text into the app via a +TextInput

    TextInput #

    A foundational component for inputting text into the app via a keyboard. Props provide configurability for several features, such as auto-correction, auto-capitalization, placeholder text, and different keyboard types, such as a numeric keypad.

    The simplest use case is to plop down a TextInput and subscribe to the @@ -7,7 +7,7 @@ such as onSubmitEditing and onFocus that can be subscr example:

    import React, { Component } from 'react'; import { AppRegistry, TextInput } from 'react-native'; -class UselessTextInput extends Component { +export default class UselessTextInput extends Component { constructor(props) { super(props); this.state = { text: 'Useless Placeholder' }; @@ -24,8 +24,8 @@ class UselessTextInput extends } } -// App registration and rendering -AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput);

    Note that some props are only available with multiline={true/false}. +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput);

    Note that some props are only available with multiline={true/false}. Additionally, border styles that apply to only one side of the element (e.g., borderBottomColor, borderLeftWidth, etc.) will not be applied if multiline=false. To achieve the same effect, you can wrap your TextInput @@ -44,7 +44,7 @@ class UselessTextInput extends } } -class UselessTextInputMultiline extends Component { +export default class UselessTextInputMultiline extends Component { constructor(props) { super(props); this.state = { @@ -72,11 +72,11 @@ class UselessTextInputMultiline extends } } -// App registration and rendering +// skip these lines if using Create React Native App AppRegistry.registerComponent( 'AwesomeProject', () => UselessTextInputMultiline -);

    TextInput has by default a border at the bottom of its view. This border +);

    TextInput has by default a border at the bottom of its view. This border has its padding set by the background image provided by the system, and it cannot be changed. Solutions to avoid this is to either not set height explicitly, case in which the system will take care of displaying the border @@ -86,1587 +86,103 @@ app's activity windowSoftInputMode param to adjustResize This may cause issues with components that have position: 'absolute' while keyboard is active. To avoid this behavior either specify windowSoftInputMode in AndroidManifest.xml ( https://developer.android.com/guide/topics/manifest/activity-element.html ) -or control this param programmatically with native code.

    Props #

    autoCapitalize?: enum('none', 'sentences', 'words', 'characters') #

    Can tell TextInput to automatically capitalize certain characters.

    • characters: all characters.
    • words: first letter of each word.
    • sentences: first letter of each sentence (default).
    • none: don't auto capitalize anything.

    autoCorrect?: bool #

    If false, disables auto-correct. The default value is true.

    autoFocus?: bool #

    If true, focuses the input on componentDidMount. -The default value is false.

    blurOnSubmit?: bool #

    If true, the text field will blur when submitted. +or control this param programmatically with native code.

    Props #

    autoCapitalize?: PropTypes.oneOf([ + 'none', + 'sentences', + 'words', + 'characters', +]) #

    Can tell TextInput to automatically capitalize certain characters.

    • characters: all characters.
    • words: first letter of each word.
    • sentences: first letter of each sentence (default).
    • none: don't auto capitalize anything.

    autoCorrect?: PropTypes.bool #

    If false, disables auto-correct. The default value is true.

    autoFocus?: PropTypes.bool #

    If true, focuses the input on componentDidMount. +The default value is false.

    blurOnSubmit?: PropTypes.bool #

    If true, the text field will blur when submitted. The default value is true for single-line fields and false for multiline fields. Note that for multiline fields, setting blurOnSubmit to true means that pressing return will blur the field and trigger the -onSubmitEditing event instead of inserting a newline into the field.

    caretHidden?: bool #

    If true, caret is hidden. The default value is false.

    defaultValue?: string #

    Provides an initial value that will change when the user starts typing. +onSubmitEditing event instead of inserting a newline into the field.

    caretHidden?: PropTypes.bool #

    If true, caret is hidden. The default value is false.

    defaultValue?: PropTypes.string #

    Provides an initial value that will change when the user starts typing. Useful for simple use-cases where you do not want to deal with listening -to events and updating the value prop to keep the controlled state in sync.

    editable?: bool #

    If false, text is not editable. The default value is true.

    keyboardType?: enum('default', 'email-address', 'numeric', 'phone-pad', 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search') #

    Determines which keyboard to open, e.g.numeric.

    The following values work across platforms:

    • default
    • numeric
    • email-address
    • phone-pad

    maxLength?: number #

    Limits the maximum number of characters that can be entered. Use this -instead of implementing the logic in JS to avoid flicker.

    multiline?: bool #

    If true, the text input can be multiple lines. -The default value is false.

    onBlur?: function #

    Callback that is called when the text input is blurred.

    onChange?: function #

    Callback that is called when the text input's text changes.

    onChangeText?: function #

    Callback that is called when the text input's text changes. -Changed text is passed as an argument to the callback handler.

    onContentSizeChange?: function #

    Callback that is called when the text input's content size changes. +to events and updating the value prop to keep the controlled state in sync.

    editable?: PropTypes.bool #

    If false, text is not editable. The default value is true.

    keyboardType?: PropTypes.oneOf([ + // Cross-platform + 'default', + 'email-address', + 'numeric', + 'phone-pad', + // iOS-only + 'ascii-capable', + 'numbers-and-punctuation', + 'url', + 'number-pad', + 'name-phone-pad', + 'decimal-pad', + 'twitter', + 'web-search', +]) #

    Determines which keyboard to open, e.g.numeric.

    The following values work across platforms:

    • default
    • numeric
    • email-address
    • phone-pad

    maxLength?: PropTypes.number #

    Limits the maximum number of characters that can be entered. Use this +instead of implementing the logic in JS to avoid flicker.

    multiline?: PropTypes.bool #

    If true, the text input can be multiple lines. +The default value is false.

    onBlur?: PropTypes.func #

    Callback that is called when the text input is blurred.

    onChange?: PropTypes.func #

    Callback that is called when the text input's text changes.

    onChangeText?: PropTypes.func #

    Callback that is called when the text input's text changes. +Changed text is passed as an argument to the callback handler.

    onContentSizeChange?: PropTypes.func #

    Callback that is called when the text input's content size changes. This will be called with -{ nativeEvent: { contentSize: { width, height } } }.

    Only called for multiline text inputs.

    onEndEditing?: function #

    Callback that is called when text input ends.

    onFocus?: function #

    Callback that is called when the text input is focused.

    onLayout?: function #

    Invoked on mount and layout changes with {x, y, width, height}.

    onScroll?: function #

    Invoked on content scroll with { nativeEvent: { contentOffset: { x, y } } }. +{ nativeEvent: { contentSize: { width, height } } }.

    Only called for multiline text inputs.

    onEndEditing?: PropTypes.func #

    Callback that is called when text input ends.

    onFocus?: PropTypes.func #

    Callback that is called when the text input is focused.

    onLayout?: PropTypes.func #

    Invoked on mount and layout changes with {x, y, width, height}.

    onScroll?: PropTypes.func #

    Invoked on content scroll with { nativeEvent: { contentOffset: { x, y } } }. May also contain other properties from ScrollEvent but on Android contentSize -is not provided for performance reasons.

    onSelectionChange?: function #

    Callback that is called when the text input selection is changed. +is not provided for performance reasons.

    onSelectionChange?: PropTypes.func #

    Callback that is called when the text input selection is changed. This will be called with -{ nativeEvent: { selection: { start, end } } }.

    onSubmitEditing?: function #

    Callback that is called when the text input's submit button is pressed. -Invalid if multiline={true} is specified.

    placeholder?: node #

    The string that will be rendered before text input has been entered.

    placeholderTextColor?: color #

    The text color of the placeholder string.

    returnKeyType?: enum('done', 'go', 'next', 'search', 'send', 'none', 'previous', 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo') #

    Determines how the return key should look. On Android you can also use -returnKeyLabel.

    Cross platform

    The following values work across platforms:

    • done
    • go
    • next
    • search
    • send

    Android Only

    The following values work on Android only:

    • none
    • previous

    iOS Only

    The following values work on iOS only:

    • default
    • emergency-call
    • google
    • join
    • route
    • yahoo

    secureTextEntry?: bool #

    If true, the text input obscures the text entered so that sensitive text -like passwords stay secure. The default value is false.

    selectTextOnFocus?: bool #

    If true, all text will automatically be selected on focus.

    selection?: {start: number, end: number} #

    The start and end of the text input's selection. Set start and end to +{ nativeEvent: { selection: { start, end } } }.

    onSubmitEditing?: PropTypes.func #

    Callback that is called when the text input's submit button is pressed. +Invalid if multiline={true} is specified.

    placeholder?: PropTypes.node #

    The string that will be rendered before text input has been entered.

    placeholderTextColor?: color #

    The text color of the placeholder string.

    returnKeyType?: PropTypes.oneOf([ + // Cross-platform + 'done', + 'go', + 'next', + 'search', + 'send', + // Android-only + 'none', + 'previous', + // iOS-only + 'default', + 'emergency-call', + 'google', + 'join', + 'route', + 'yahoo', +]) #

    Determines how the return key should look. On Android you can also use +returnKeyLabel.

    Cross platform

    The following values work across platforms:

    • done
    • go
    • next
    • search
    • send

    Android Only

    The following values work on Android only:

    • none
    • previous

    iOS Only

    The following values work on iOS only:

    • default
    • emergency-call
    • google
    • join
    • route
    • yahoo

    secureTextEntry?: PropTypes.bool #

    If true, the text input obscures the text entered so that sensitive text +like passwords stay secure. The default value is false.

    selectTextOnFocus?: PropTypes.bool #

    If true, all text will automatically be selected on focus.

    selection?: PropTypes.shape({ + start: PropTypes.number.isRequired, + end: PropTypes.number, +}) #

    The start and end of the text input's selection. Set start and end to the same value to position the cursor.

    selectionColor?: color #

    The highlight and cursor color of the text input.

    style?: Text#style #

    Note that not all Text styles are supported, see Issue#7070 -for more detail.

    Styles

    value?: string #

    The value to show for the text input. TextInput is a controlled +for more detail.

    Styles

    value?: PropTypes.string #

    The value to show for the text input. TextInput is a controlled component, which means the native value will be forced to match this value prop if provided. For most uses, this works great, but in some cases this may cause flickering - one common cause is preventing edits by keeping value the same. In addition to simply setting the same value, either set editable={false}, or set/update maxLength to prevent -unwanted edits without flicker.

    androiddisableFullscreenUI?: bool #

    When false, if there is a small amount of space available around a text input +unwanted edits without flicker.

    androiddisableFullscreenUI?: PropTypes.bool #

    When false, if there is a small amount of space available around a text input (e.g. landscape orientation on a phone), the OS may choose to have the user edit the text inside of a full screen text input mode. When true, this feature is disabled and users will always edit the text directly inside of the text input. -Defaults to false.

    androidinlineImageLeft?: string #

    If defined, the provided image resource will be rendered on the left.

    androidinlineImagePadding?: number #

    Padding between the inline image, if any, and the text input itself.

    androidnumberOfLines?: number #

    Sets the number of lines for a TextInput. Use it with multiline set to -true to be able to fill the lines.

    androidreturnKeyLabel?: string #

    Sets the return key to the label. Use it instead of returnKeyType.

    androidtextBreakStrategy?: enum('simple', 'highQuality', 'balanced') #

    Set text break strategy on Android API Level 23+, possible values are simple, highQuality, balanced -The default value is simple.

    androidunderlineColorAndroid?: color #

    The color of the TextInput underline.

    iosclearButtonMode?: enum('never', 'while-editing', 'unless-editing', 'always') #

    When the clear button should appear on the right side of the text view.

    iosclearTextOnFocus?: bool #

    If true, clears the text field automatically when editing begins.

    iosdataDetectorTypes?: enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all'), [enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all')] #

    Determines the types of data converted to clickable URLs in the text input. +Defaults to false.

    androidinlineImageLeft?: PropTypes.string #

    If defined, the provided image resource will be rendered on the left.

    androidinlineImagePadding?: PropTypes.number #

    Padding between the inline image, if any, and the text input itself.

    androidnumberOfLines?: PropTypes.number #

    Sets the number of lines for a TextInput. Use it with multiline set to +true to be able to fill the lines.

    androidreturnKeyLabel?: PropTypes.string #

    Sets the return key to the label. Use it instead of returnKeyType.

    androidtextBreakStrategy?: PropTypes.oneOf(['simple', 'highQuality', 'balanced']) #

    Set text break strategy on Android API Level 23+, possible values are simple, highQuality, balanced +The default value is simple.

    androidunderlineColorAndroid?: color #

    The color of the TextInput underline.

    iosclearButtonMode?: PropTypes.oneOf([ + 'never', + 'while-editing', + 'unless-editing', + 'always', +]) #

    When the clear button should appear on the right side of the text view.

    iosclearTextOnFocus?: PropTypes.bool #

    If true, clears the text field automatically when editing begins.

    iosdataDetectorTypes?: PropTypes.oneOfType([ + PropTypes.oneOf(DataDetectorTypes), + PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), +]) #

    Determines the types of data converted to clickable URLs in the text input. Only valid if multiline={true} and editable={false}. -By default no data types are detected.

    You can provide one type or an array of many types.

    Possible values for dataDetectorTypes are:

    • 'phoneNumber'
    • 'link'
    • 'address'
    • 'calendarEvent'
    • 'none'
    • 'all'

    iosenablesReturnKeyAutomatically?: bool #

    If true, the keyboard disables the return key when there is no text and -automatically enables it when there is text. The default value is false.

    ioskeyboardAppearance?: enum('default', 'light', 'dark') #

    Determines the color of the keyboard.

    iosonKeyPress?: function #

    Callback that is called when a key is pressed. +By default no data types are detected.

    You can provide one type or an array of many types.

    Possible values for dataDetectorTypes are:

    • 'phoneNumber'
    • 'link'
    • 'address'
    • 'calendarEvent'
    • 'none'
    • 'all'

    iosenablesReturnKeyAutomatically?: PropTypes.bool #

    If true, the keyboard disables the return key when there is no text and +automatically enables it when there is text. The default value is false.

    ioskeyboardAppearance?: PropTypes.oneOf([ + 'default', + 'light', + 'dark', +]) #

    Determines the color of the keyboard.

    iosonKeyPress?: PropTypes.func #

    Callback that is called when a key is pressed. This will be called with { nativeEvent: { key: keyValue } } where keyValue is 'Enter' or 'Backspace' for respective keys and the typed-in character otherwise including ' ' for space. -Fires before onChange callbacks.

    iosselectionState?: DocumentSelectionState #

    An instance of DocumentSelectionState, this is some state that is responsible for +Fires before onChange callbacks.

    iosselectionState?: PropTypes.instanceOf(DocumentSelectionState) #

    An instance of DocumentSelectionState, this is some state that is responsible for maintaining selection information for a document.

    Some functionality that can be performed with this instance is:

    • blur()
    • focus()
    • update()

    You can reference DocumentSelectionState in -vendor/document/selection/DocumentSelectionState.js

    iosspellCheck?: bool #

    If false, disables spell-check style (i.e. red underlines). -The default value is inherited from autoCorrect.

    Methods #

    isFocused(): #

    Returns true if the input is currently focused; false otherwise.

    clear() #

    Removes all text from the TextInput.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    IOS #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - Text, - TextInput, - View, - StyleSheet, -} = ReactNative; - -class WithLabel extends React.Component { - render() { - return ( - <View style={styles.labelContainer}> - <View style={styles.label}> - <Text>{this.props.label}</Text> - </View> - {this.props.children} - </View> - ); - } -} - -class TextEventsExample extends React.Component { - state = { - curText: '<No Event>', - prevText: '<No Event>', - prev2Text: '<No Event>', - prev3Text: '<No Event>', - }; - - updateText = (text) => { - this.setState((state) => { - return { - curText: text, - prevText: state.curText, - prev2Text: state.prevText, - prev3Text: state.prev2Text, - }; - }); - }; - - render() { - return ( - <View> - <TextInput - autoCapitalize="none" - placeholder="Enter text to see events" - autoCorrect={false} - onFocus={() => this.updateText('onFocus')} - onBlur={() => this.updateText('onBlur')} - onChange={(event) => this.updateText( - 'onChange text: ' + event.nativeEvent.text - )} - onEndEditing={(event) => this.updateText( - 'onEndEditing text: ' + event.nativeEvent.text - )} - onSubmitEditing={(event) => this.updateText( - 'onSubmitEditing text: ' + event.nativeEvent.text - )} - onSelectionChange={(event) => this.updateText( - 'onSelectionChange range: ' + - event.nativeEvent.selection.start + ',' + - event.nativeEvent.selection.end - )} - onKeyPress={(event) => { - this.updateText('onKeyPress key: ' + event.nativeEvent.key); - }} - style={styles.default} - /> - <Text style={styles.eventLabel}> - {this.state.curText}{'\n'} - (prev: {this.state.prevText}){'\n'} - (prev2: {this.state.prev2Text}){'\n'} - (prev3: {this.state.prev3Text}) - </Text> - </View> - ); - } -} - -class RewriteExample extends React.Component { - state: any; - - constructor(props) { - super(props); - this.state = {text: ''}; - } - render() { - var limit = 20; - var remainder = limit - this.state.text.length; - var remainderColor = remainder > 5 ? 'blue' : 'red'; - return ( - <View style={styles.rewriteContainer}> - <TextInput - multiline={false} - maxLength={limit} - onChangeText={(text) => { - text = text.replace(/ /g, '_'); - this.setState({text}); - }} - style={styles.default} - value={this.state.text} - /> - <Text style={[styles.remainder, {color: remainderColor}]}> - {remainder} - </Text> - </View> - ); - } -} - -class RewriteExampleInvalidCharacters extends React.Component { - state: any; - - constructor(props) { - super(props); - this.state = {text: ''}; - } - render() { - return ( - <View style={styles.rewriteContainer}> - <TextInput - multiline={false} - onChangeText={(text) => { - this.setState({text: text.replace(/\s/g, '')}); - }} - style={styles.default} - value={this.state.text} - /> - </View> - ); - } -} - -class TokenizedTextExample extends React.Component { - state: any; - - constructor(props) { - super(props); - this.state = {text: 'Hello #World'}; - } - render() { - - //define delimiter - let delimiter = /\s+/; - - //split string - let _text = this.state.text; - let token, index, parts = []; - while (_text) { - delimiter.lastIndex = 0; - token = delimiter.exec(_text); - if (token === null) { - break; - } - index = token.index; - if (token[0].length === 0) { - index = 1; - } - parts.push(_text.substr(0, index)); - parts.push(token[0]); - index = index + token[0].length; - _text = _text.slice(index); - } - parts.push(_text); - - //highlight hashtags - parts = parts.map((text) => { - if (/^#/.test(text)) { - return <Text key={text} style={styles.hashtag}>{text}</Text>; - } else { - return text; - } - }); - - return ( - <View> - <TextInput - multiline={true} - style={styles.multiline} - onChangeText={(text) => { - this.setState({text}); - }}> - <Text>{parts}</Text> - </TextInput> - </View> - ); - } -} - -class BlurOnSubmitExample extends React.Component { - focusNextField = (nextField) => { - this.refs[nextField].focus(); - }; - - render() { - return ( - <View> - <TextInput - ref="1" - style={styles.default} - placeholder="blurOnSubmit = false" - returnKeyType="next" - blurOnSubmit={false} - onSubmitEditing={() => this.focusNextField('2')} - /> - <TextInput - ref="2" - style={styles.default} - keyboardType="email-address" - placeholder="blurOnSubmit = false" - returnKeyType="next" - blurOnSubmit={false} - onSubmitEditing={() => this.focusNextField('3')} - /> - <TextInput - ref="3" - style={styles.default} - keyboardType="url" - placeholder="blurOnSubmit = false" - returnKeyType="next" - blurOnSubmit={false} - onSubmitEditing={() => this.focusNextField('4')} - /> - <TextInput - ref="4" - style={styles.default} - keyboardType="numeric" - placeholder="blurOnSubmit = false" - blurOnSubmit={false} - onSubmitEditing={() => this.focusNextField('5')} - /> - <TextInput - ref="5" - style={styles.default} - keyboardType="numbers-and-punctuation" - placeholder="blurOnSubmit = true" - returnKeyType="done" - /> - </View> - ); - } -} - -type SelectionExampleState = { - selection: { - start: number; - end?: number; - }; - value: string; -}; - -class SelectionExample extends React.Component { - state: SelectionExampleState; - - _textInput: any; - - constructor(props) { - super(props); - this.state = { - selection: {start: 0, end: 0}, - value: props.value - }; - } - - onSelectionChange({nativeEvent: {selection}}) { - this.setState({selection}); - } - - getRandomPosition() { - var length = this.state.value.length; - return Math.round(Math.random() * length); - } - - select(start, end) { - this._textInput.focus(); - this.setState({selection: {start, end}}); - } - - selectRandom() { - var positions = [this.getRandomPosition(), this.getRandomPosition()].sort(); - this.select(...positions); - } - - placeAt(position) { - this.select(position, position); - } - - placeAtRandom() { - this.placeAt(this.getRandomPosition()); - } - - render() { - var length = this.state.value.length; - - return ( - <View> - <TextInput - multiline={this.props.multiline} - onChangeText={(value) => this.setState({value})} - onSelectionChange={this.onSelectionChange.bind(this)} - ref={textInput => (this._textInput = textInput)} - selection={this.state.selection} - style={this.props.style} - value={this.state.value} - /> - <View> - <Text> - selection = {JSON.stringify(this.state.selection)} - </Text> - <Text onPress={this.placeAt.bind(this, 0)}> - Place at Start (0, 0) - </Text> - <Text onPress={this.placeAt.bind(this, length)}> - Place at End ({length}, {length}) - </Text> - <Text onPress={this.placeAtRandom.bind(this)}> - Place at Random - </Text> - <Text onPress={this.select.bind(this, 0, length)}> - Select All - </Text> - <Text onPress={this.selectRandom.bind(this)}> - Select Random - </Text> - </View> - </View> - ); - } -} - -var styles = StyleSheet.create({ - page: { - paddingBottom: 300, - }, - default: { - height: 26, - borderWidth: 0.5, - borderColor: '#0f0f0f', - flex: 1, - fontSize: 13, - padding: 4, - }, - multiline: { - borderWidth: 0.5, - borderColor: '#0f0f0f', - flex: 1, - fontSize: 13, - height: 50, - padding: 4, - marginBottom: 4, - }, - multilineExpandable: { - height: 'auto', - maxHeight: 100, - }, - multilineWithFontStyles: { - color: 'blue', - fontWeight: 'bold', - fontSize: 18, - fontFamily: 'Cochin', - height: 60, - }, - multilineChild: { - width: 50, - height: 40, - position: 'absolute', - right: 5, - backgroundColor: 'red', - }, - eventLabel: { - margin: 3, - fontSize: 12, - }, - labelContainer: { - flexDirection: 'row', - marginVertical: 2, - flex: 1, - }, - label: { - width: 115, - alignItems: 'flex-end', - marginRight: 10, - paddingTop: 2, - }, - rewriteContainer: { - flexDirection: 'row', - alignItems: 'center', - }, - remainder: { - textAlign: 'right', - width: 24, - }, - hashtag: { - color: 'blue', - fontWeight: 'bold', - }, -}); - -exports.displayName = (undefined: ?string); -exports.title = '<TextInput>'; -exports.description = 'Single and multi-line text inputs.'; -exports.examples = [ - { - title: 'Auto-focus', - render: function() { - return ( - <TextInput - autoFocus={true} - style={styles.default} - accessibilityLabel="I am the accessibility label for text input" - /> - ); - } - }, - { - title: "Live Re-Write (<sp> -> '_') + maxLength", - render: function() { - return <RewriteExample />; - } - }, - { - title: 'Live Re-Write (no spaces allowed)', - render: function() { - return <RewriteExampleInvalidCharacters />; - } - }, - { - title: 'Auto-capitalize', - render: function() { - return ( - <View> - <WithLabel label="none"> - <TextInput - autoCapitalize="none" - style={styles.default} - /> - </WithLabel> - <WithLabel label="sentences"> - <TextInput - autoCapitalize="sentences" - style={styles.default} - /> - </WithLabel> - <WithLabel label="words"> - <TextInput - autoCapitalize="words" - style={styles.default} - /> - </WithLabel> - <WithLabel label="characters"> - <TextInput - autoCapitalize="characters" - style={styles.default} - /> - </WithLabel> - </View> - ); - } - }, - { - title: 'Auto-correct', - render: function() { - return ( - <View> - <WithLabel label="true"> - <TextInput autoCorrect={true} style={styles.default} /> - </WithLabel> - <WithLabel label="false"> - <TextInput autoCorrect={false} style={styles.default} /> - </WithLabel> - </View> - ); - } - }, - { - title: 'Keyboard types', - render: function() { - var keyboardTypes = [ - 'default', - 'ascii-capable', - 'numbers-and-punctuation', - 'url', - 'number-pad', - 'phone-pad', - 'name-phone-pad', - 'email-address', - 'decimal-pad', - 'twitter', - 'web-search', - 'numeric', - ]; - var examples = keyboardTypes.map((type) => { - return ( - <WithLabel key={type} label={type}> - <TextInput - keyboardType={type} - style={styles.default} - /> - </WithLabel> - ); - }); - return <View>{examples}</View>; - } - }, - { - title: 'Keyboard appearance', - render: function() { - var keyboardAppearance = [ - 'default', - 'light', - 'dark', - ]; - var examples = keyboardAppearance.map((type) => { - return ( - <WithLabel key={type} label={type}> - <TextInput - keyboardAppearance={type} - style={styles.default} - /> - </WithLabel> - ); - }); - return <View>{examples}</View>; - } - }, - { - title: 'Return key types', - render: function() { - var returnKeyTypes = [ - 'default', - 'go', - 'google', - 'join', - 'next', - 'route', - 'search', - 'send', - 'yahoo', - 'done', - 'emergency-call', - ]; - var examples = returnKeyTypes.map((type) => { - return ( - <WithLabel key={type} label={type}> - <TextInput - returnKeyType={type} - style={styles.default} - /> - </WithLabel> - ); - }); - return <View>{examples}</View>; - } - }, - { - title: 'Enable return key automatically', - render: function() { - return ( - <View> - <WithLabel label="true"> - <TextInput enablesReturnKeyAutomatically={true} style={styles.default} /> - </WithLabel> - </View> - ); - } - }, - { - title: 'Secure text entry', - render: function() { - return ( - <View> - <WithLabel label="true"> - <TextInput secureTextEntry={true} style={styles.default} defaultValue="abc" /> - </WithLabel> - </View> - ); - } - }, - { - title: 'Event handling', - render: function(): React.Element<any> { return <TextEventsExample />; }, - }, - { - title: 'Colored input text', - render: function() { - return ( - <View> - <TextInput - style={[styles.default, {color: 'blue'}]} - defaultValue="Blue" - /> - <TextInput - style={[styles.default, {color: 'green'}]} - defaultValue="Green" - /> - </View> - ); - } - }, - { - title: 'Colored highlight/cursor for text input', - render: function() { - return ( - <View> - <TextInput - style={styles.default} - selectionColor={"green"} - defaultValue="Highlight me" - /> - <TextInput - style={styles.default} - selectionColor={"rgba(86, 76, 205, 1)"} - defaultValue="Highlight me" - /> - </View> - ); - } - }, - { - title: 'Clear button mode', - render: function () { - return ( - <View> - <WithLabel label="never"> - <TextInput - style={styles.default} - clearButtonMode="never" - /> - </WithLabel> - <WithLabel label="while editing"> - <TextInput - style={styles.default} - clearButtonMode="while-editing" - /> - </WithLabel> - <WithLabel label="unless editing"> - <TextInput - style={styles.default} - clearButtonMode="unless-editing" - /> - </WithLabel> - <WithLabel label="always"> - <TextInput - style={styles.default} - clearButtonMode="always" - /> - </WithLabel> - </View> - ); - } - }, - { - title: 'Clear and select', - render: function() { - return ( - <View> - <WithLabel label="clearTextOnFocus"> - <TextInput - placeholder="text is cleared on focus" - defaultValue="text is cleared on focus" - style={styles.default} - clearTextOnFocus={true} - /> - </WithLabel> - <WithLabel label="selectTextOnFocus"> - <TextInput - placeholder="text is selected on focus" - defaultValue="text is selected on focus" - style={styles.default} - selectTextOnFocus={true} - /> - </WithLabel> - </View> - ); - } - }, - { - title: 'Blur on submit', - render: function(): React.Element<any> { return <BlurOnSubmitExample />; }, - }, - { - title: 'Multiline blur on submit', - render: function() { - return ( - <View> - <TextInput - style={styles.multiline} - placeholder="blurOnSubmit = true" - returnKeyType="next" - blurOnSubmit={true} - multiline={true} - onSubmitEditing={event => alert(event.nativeEvent.text)} - /> - </View> - ); - } - }, - { - title: 'Multiline', - render: function() { - return ( - <View> - <TextInput - placeholder="multiline text input" - multiline={true} - style={styles.multiline} - /> - <TextInput - placeholder="multiline text input with font styles and placeholder" - multiline={true} - clearTextOnFocus={true} - autoCorrect={true} - autoCapitalize="words" - placeholderTextColor="red" - keyboardType="url" - style={[styles.multiline, styles.multilineWithFontStyles]} - /> - <TextInput - placeholder="multiline text input with max length" - maxLength={5} - multiline={true} - style={styles.multiline} - /> - <TextInput - placeholder="uneditable multiline text input" - editable={false} - multiline={true} - style={styles.multiline} - /> - <TextInput - defaultValue="uneditable multiline text input with phone number detection: 88888888." - editable={false} - multiline={true} - style={styles.multiline} - dataDetectorTypes="phoneNumber" - /> - <TextInput - placeholder="multiline with children" - multiline={true} - enablesReturnKeyAutomatically={true} - returnKeyType="go" - style={styles.multiline}> - <View style={styles.multilineChild}/> - </TextInput> - </View> - ); - } - }, - { - title: 'Auto-expanding', - render: function() { - return ( - <View> - <TextInput - placeholder="height increases with content" - defaultValue="React Native enables you to build world-class application experiences on native platforms using a consistent developer experience based on JavaScript and React. The focus of React Native is on developer efficiency across all the platforms you care about - learn once, write anywhere. Facebook uses React Native in multiple production apps and will continue investing in React Native." - multiline={true} - enablesReturnKeyAutomatically={true} - returnKeyType="go" - style={[styles.multiline, styles.multilineExpandable]} - /> - </View> - ); - } - }, - { - title: 'Attributed text', - render: function() { - return <TokenizedTextExample />; - } - }, - { - title: 'Text selection & cursor placement', - render: function() { - return ( - <View> - <SelectionExample - style={styles.default} - value="text selection can be changed" - /> - <SelectionExample - multiline - style={styles.multiline} - value={"multiline text selection\ncan also be changed"} - /> - </View> - ); - } - }, - { - title: 'TextInput maxLength', - render: function() { - return ( - <View> - <WithLabel label="maxLength: 5"> - <TextInput - maxLength={5} - style={styles.default} - /> - </WithLabel> - <WithLabel label="maxLength: 5 with placeholder"> - <TextInput - maxLength={5} - placeholder="ZIP code entry" - style={styles.default} - /> - </WithLabel> - <WithLabel label="maxLength: 5 with default value already set"> - <TextInput - maxLength={5} - defaultValue="94025" - style={styles.default} - /> - </WithLabel> - <WithLabel label="maxLength: 5 with very long default value already set"> - <TextInput - maxLength={5} - defaultValue="9402512345" - style={styles.default} - /> - </WithLabel> - </View> - ); - } - }, -];

    ANDROID #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - Text, - TextInput, - View, - StyleSheet, -} = ReactNative; - -class TextEventsExample extends React.Component { - state = { - curText: '<No Event>', - prevText: '<No Event>', - prev2Text: '<No Event>', - }; - - updateText = (text) => { - this.setState((state) => { - return { - curText: text, - prevText: state.curText, - prev2Text: state.prevText, - }; - }); - }; - - render() { - return ( - <View> - <TextInput - autoCapitalize="none" - placeholder="Enter text to see events" - autoCorrect={false} - onFocus={() => this.updateText('onFocus')} - onBlur={() => this.updateText('onBlur')} - onChange={(event) => this.updateText( - 'onChange text: ' + event.nativeEvent.text - )} - onEndEditing={(event) => this.updateText( - 'onEndEditing text: ' + event.nativeEvent.text - )} - onSubmitEditing={(event) => this.updateText( - 'onSubmitEditing text: ' + event.nativeEvent.text - )} - style={styles.singleLine} - /> - <Text style={styles.eventLabel}> - {this.state.curText}{'\n'} - (prev: {this.state.prevText}){'\n'} - (prev2: {this.state.prev2Text}) - </Text> - </View> - ); - } -} - -class AutoExpandingTextInput extends React.Component { - constructor(props) { - super(props); - this.state = { - text: 'React Native enables you to build world-class application experiences on native platforms using a consistent developer experience based on JavaScript and React. The focus of React Native is on developer efficiency across all the platforms you care about — learn once, write anywhere. Facebook uses React Native in multiple production apps and will continue investing in React Native.', - height: 0, - }; - } - render() { - return ( - <TextInput - {...this.props} - multiline={true} - onContentSizeChange={(event) => { - this.setState({height: event.nativeEvent.contentSize.height}); - }} - onChangeText={(text) => { - this.setState({text}); - }} - style={[styles.default, {height: Math.max(35, this.state.height)}]} - value={this.state.text} - /> - ); - } -} - -class RewriteExample extends React.Component { - constructor(props) { - super(props); - this.state = {text: ''}; - } - render() { - var limit = 20; - var remainder = limit - this.state.text.length; - var remainderColor = remainder > 5 ? 'blue' : 'red'; - return ( - <View style={styles.rewriteContainer}> - <TextInput - multiline={false} - maxLength={limit} - onChangeText={(text) => { - text = text.replace(/ /g, '_'); - this.setState({text}); - }} - style={styles.default} - value={this.state.text} - /> - <Text style={[styles.remainder, {color: remainderColor}]}> - {remainder} - </Text> - </View> - ); - } -} - -class TokenizedTextExample extends React.Component { - constructor(props) { - super(props); - this.state = {text: 'Hello #World'}; - } - render() { - - //define delimiter - let delimiter = /\s+/; - - //split string - let _text = this.state.text; - let token, index, parts = []; - while (_text) { - delimiter.lastIndex = 0; - token = delimiter.exec(_text); - if (token === null) { - break; - } - index = token.index; - if (token[0].length === 0) { - index = 1; - } - parts.push(_text.substr(0, index)); - parts.push(token[0]); - index = index + token[0].length; - _text = _text.slice(index); - } - parts.push(_text); - - //highlight hashtags - parts = parts.map((text) => { - if (/^#/.test(text)) { - return <Text key={text} style={styles.hashtag}>{text}</Text>; - } else { - return text; - } - }); - - return ( - <View> - <TextInput - multiline={true} - style={styles.multiline} - onChangeText={(text) => { - this.setState({text}); - }}> - <Text>{parts}</Text> - </TextInput> - </View> - ); - } -} - -class BlurOnSubmitExample extends React.Component { - focusNextField = (nextField) => { - this.refs[nextField].focus(); - }; - - render() { - return ( - <View> - <TextInput - ref="1" - style={styles.singleLine} - placeholder="blurOnSubmit = false" - returnKeyType="next" - blurOnSubmit={false} - onSubmitEditing={() => this.focusNextField('2')} - /> - <TextInput - ref="2" - style={styles.singleLine} - keyboardType="email-address" - placeholder="blurOnSubmit = false" - returnKeyType="next" - blurOnSubmit={false} - onSubmitEditing={() => this.focusNextField('3')} - /> - <TextInput - ref="3" - style={styles.singleLine} - keyboardType="url" - placeholder="blurOnSubmit = false" - returnKeyType="next" - blurOnSubmit={false} - onSubmitEditing={() => this.focusNextField('4')} - /> - <TextInput - ref="4" - style={styles.singleLine} - keyboardType="numeric" - placeholder="blurOnSubmit = false" - blurOnSubmit={false} - onSubmitEditing={() => this.focusNextField('5')} - /> - <TextInput - ref="5" - style={styles.singleLine} - keyboardType="numbers-and-punctuation" - placeholder="blurOnSubmit = true" - returnKeyType="done" - /> - </View> - ); - } -} - -class ToggleDefaultPaddingExample extends React.Component { - constructor(props) { - super(props); - this.state = {hasPadding: false}; - } - render() { - return ( - <View> - <TextInput style={this.state.hasPadding ? { padding: 0 } : null}/> - <Text onPress={() => this.setState({hasPadding: !this.state.hasPadding})}> - Toggle padding - </Text> - </View> - ); - } -} - -type SelectionExampleState = { - selection: { - start: number; - end: number; - }; - value: string; -}; - -class SelectionExample extends React.Component { - state: SelectionExampleState; - - _textInput: any; - - constructor(props) { - super(props); - this.state = { - selection: {start: 0, end: 0}, - value: props.value - }; - } - - onSelectionChange({nativeEvent: {selection}}) { - this.setState({selection}); - } - - getRandomPosition() { - var length = this.state.value.length; - return Math.round(Math.random() * length); - } - - select(start, end) { - this._textInput.focus(); - this.setState({selection: {start, end}}); - } - - selectRandom() { - var positions = [this.getRandomPosition(), this.getRandomPosition()].sort(); - this.select(...positions); - } - - placeAt(position) { - this.select(position, position); - } - - placeAtRandom() { - this.placeAt(this.getRandomPosition()); - } - - render() { - var length = this.state.value.length; - - return ( - <View> - <TextInput - multiline={this.props.multiline} - onChangeText={(value) => this.setState({value})} - onSelectionChange={this.onSelectionChange.bind(this)} - ref={textInput => (this._textInput = textInput)} - selection={this.state.selection} - style={this.props.style} - value={this.state.value} - /> - <View> - <Text> - selection = {JSON.stringify(this.state.selection)} - </Text> - <Text onPress={this.placeAt.bind(this, 0)}> - Place at Start (0, 0) - </Text> - <Text onPress={this.placeAt.bind(this, length)}> - Place at End ({length}, {length}) - </Text> - <Text onPress={this.placeAtRandom.bind(this)}> - Place at Random - </Text> - <Text onPress={this.select.bind(this, 0, length)}> - Select All - </Text> - <Text onPress={this.selectRandom.bind(this)}> - Select Random - </Text> - </View> - </View> - ); - } -} - -var styles = StyleSheet.create({ - multiline: { - height: 60, - fontSize: 16, - padding: 4, - marginBottom: 10, - }, - eventLabel: { - margin: 3, - fontSize: 12, - }, - singleLine: { - fontSize: 16, - padding: 4, - }, - singleLineWithHeightTextInput: { - height: 30, - }, - hashtag: { - color: 'blue', - fontWeight: 'bold', - }, -}); - -exports.title = '<TextInput>'; -exports.description = 'Single and multi-line text inputs.'; -exports.examples = [ - { - title: 'Auto-focus', - render: function() { - return ( - <TextInput - autoFocus={true} - style={styles.singleLine} - accessibilityLabel="I am the accessibility label for text input" - /> - ); - } - }, - { - title: "Live Re-Write (<sp> -> '_')", - render: function() { - return <RewriteExample />; - } - }, - { - title: 'Auto-capitalize', - render: function() { - var autoCapitalizeTypes = [ - 'none', - 'sentences', - 'words', - 'characters', - ]; - var examples = autoCapitalizeTypes.map((type) => { - return ( - <TextInput - key={type} - autoCapitalize={type} - placeholder={'autoCapitalize: ' + type} - style={styles.singleLine} - /> - ); - }); - return <View>{examples}</View>; - } - }, - { - title: 'Auto-correct', - render: function() { - return ( - <View> - <TextInput - autoCorrect={true} - placeholder="This has autoCorrect" - style={styles.singleLine} - /> - <TextInput - autoCorrect={false} - placeholder="This does not have autoCorrect" - style={styles.singleLine} - /> - </View> - ); - } - }, - { - title: 'Keyboard types', - render: function() { - var keyboardTypes = [ - 'default', - 'email-address', - 'numeric', - 'phone-pad', - ]; - var examples = keyboardTypes.map((type) => { - return ( - <TextInput - key={type} - keyboardType={type} - placeholder={'keyboardType: ' + type} - style={styles.singleLine} - /> - ); - }); - return <View>{examples}</View>; - } - }, - { - title: 'Blur on submit', - render: function(): React.Element { return <BlurOnSubmitExample />; }, - }, - { - title: 'Event handling', - render: function(): React.Element { return <TextEventsExample />; }, - }, - { - title: 'Colors and text inputs', - render: function() { - return ( - <View> - <TextInput - style={[styles.singleLine]} - defaultValue="Default color text" - /> - <TextInput - style={[styles.singleLine, {color: 'green'}]} - defaultValue="Green Text" - /> - <TextInput - placeholder="Default placeholder text color" - style={styles.singleLine} - /> - <TextInput - placeholder="Red placeholder text color" - placeholderTextColor="red" - style={styles.singleLine} - /> - <TextInput - placeholder="Default underline color" - style={styles.singleLine} - /> - <TextInput - placeholder="Blue underline color" - style={styles.singleLine} - underlineColorAndroid="blue" - /> - <TextInput - defaultValue="Same BackgroundColor as View " - style={[styles.singleLine, {backgroundColor: 'rgba(100, 100, 100, 0.3)'}]}> - <Text style={{backgroundColor: 'rgba(100, 100, 100, 0.3)'}}> - Darker backgroundColor - </Text> - </TextInput> - <TextInput - defaultValue="Highlight Color is red" - selectionColor={'red'} - style={styles.singleLine}> - </TextInput> - </View> - ); - } - }, - { - title: 'Text input, themes and heights', - render: function() { - return ( - <TextInput - placeholder="If you set height, beware of padding set from themes" - style={[styles.singleLineWithHeightTextInput]} - /> - ); - } - }, - { - title: 'fontFamily, fontWeight and fontStyle', - render: function() { - return ( - <View> - <TextInput - style={[styles.singleLine, {fontFamily: 'sans-serif'}]} - placeholder="Custom fonts like Sans-Serif are supported" - /> - <TextInput - style={[styles.singleLine, {fontFamily: 'sans-serif', fontWeight: 'bold'}]} - placeholder="Sans-Serif bold" - /> - <TextInput - style={[styles.singleLine, {fontFamily: 'sans-serif', fontStyle: 'italic'}]} - placeholder="Sans-Serif italic" - /> - <TextInput - style={[styles.singleLine, {fontFamily: 'serif'}]} - placeholder="Serif" - /> - </View> - ); - } - }, - { - title: 'Passwords', - render: function() { - return ( - <View> - <TextInput - defaultValue="iloveturtles" - secureTextEntry={true} - style={styles.singleLine} - /> - <TextInput - secureTextEntry={true} - style={[styles.singleLine, {color: 'red'}]} - placeholder="color is supported too" - placeholderTextColor="red" - /> - </View> - ); - } - }, - { - title: 'Editable', - render: function() { - return ( - <TextInput - defaultValue="Can't touch this! (>'-')> ^(' - ')^ <('-'<) (>'-')> ^(' - ')^" - editable={false} - style={styles.singleLine} - /> - ); - } - }, - { - title: 'Multiline', - render: function() { - return ( - <View> - <TextInput - autoCorrect={true} - placeholder="multiline, aligned top-left" - placeholderTextColor="red" - multiline={true} - style={[styles.multiline, {textAlign: 'left', textAlignVertical: 'top'}]} - /> - <TextInput - autoCorrect={true} - placeholder="multiline, aligned center" - placeholderTextColor="green" - multiline={true} - style={[styles.multiline, {textAlign: 'center', textAlignVertical: 'center'}]} - /> - <TextInput - autoCorrect={true} - multiline={true} - style={[styles.multiline, {color: 'blue'}, {textAlign: 'right', textAlignVertical: 'bottom'}]}> - <Text style={styles.multiline}>multiline with children, aligned bottom-right</Text> - </TextInput> - </View> - ); - } - }, - { - title: 'Fixed number of lines', - platform: 'android', - render: function() { - return ( - <View> - <TextInput numberOfLines={2} - multiline={true} - placeholder="Two line input" - /> - <TextInput numberOfLines={5} - multiline={true} - placeholder="Five line input" - /> - </View> - ); - } - }, - { - title: 'Auto-expanding', - render: function() { - return ( - <View> - <AutoExpandingTextInput - placeholder="height increases with content" - enablesReturnKeyAutomatically={true} - returnKeyType="done" - /> - </View> - ); - } - }, - { - title: 'Attributed text', - render: function() { - return <TokenizedTextExample />; - } - }, - { - title: 'Return key', - render: function() { - var returnKeyTypes = [ - 'none', - 'go', - 'search', - 'send', - 'done', - 'previous', - 'next', - ]; - var returnKeyLabels = [ - 'Compile', - 'React Native', - ]; - var examples = returnKeyTypes.map((type) => { - return ( - <TextInput - key={type} - returnKeyType={type} - placeholder={'returnKeyType: ' + type} - style={styles.singleLine} - /> - ); - }); - var types = returnKeyLabels.map((type) => { - return ( - <TextInput - key={type} - returnKeyLabel={type} - placeholder={'returnKeyLabel: ' + type} - style={styles.singleLine} - /> - ); - }); - return <View>{examples}{types}</View>; - } - }, - { - title: 'Inline Images', - render: function() { - return ( - <View> - <TextInput - inlineImageLeft="ic_menu_black_24dp" - placeholder="This has drawableLeft set" - style={styles.singleLine} - /> - <TextInput - inlineImageLeft="ic_menu_black_24dp" - inlineImagePadding={30} - placeholder="This has drawableLeft and drawablePadding set" - style={styles.singleLine} - /> - <TextInput - placeholder="This does not have drawable props set" - style={styles.singleLine} - /> - </View> - ); - } - }, - { - title: 'Toggle Default Padding', - render: function(): React.Element { return <ToggleDefaultPaddingExample />; }, - }, - { - title: 'Text selection & cursor placement', - render: function() { - return ( - <View> - <SelectionExample - style={styles.default} - value="text selection can be changed" - /> - <SelectionExample - multiline - style={styles.multiline} - value={"multiline text selection\ncan also be changed"} - /> - </View> - ); - } - }, -];
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/timepickerandroid.html b/docs/timepickerandroid.html index 6017ddcd377..216533788d9 100644 --- a/docs/timepickerandroid.html +++ b/docs/timepickerandroid.html @@ -1,4 +1,4 @@ -TimePickerAndroid

    TimePickerAndroid #

    Opens the standard Android time picker dialog.

    Example #

    try { +TimePickerAndroid

    TimePickerAndroid #

    Opens the standard Android time picker dialog.

    Example #

    try { const {action, hour, minute} = await TimePickerAndroid.open({ hour: 14, minute: 0, @@ -17,97 +17,7 @@ is used.

    Returns a Promise which will be invoked an object containing action, hour (0-23), minute (0-59) if the user picked a time. If the user dismissed the dialog, the Promise will still be resolved with action being TimePickerAndroid.dismissedAction and all the other keys -being undefined. Always check whether the action before reading the values.

    static timeSetAction() #

    A time has been selected.

    static dismissedAction() #

    The dialog has been dismissed.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - TimePickerAndroid, - StyleSheet, - Text, - TouchableWithoutFeedback, -} = ReactNative; - -var UIExplorerBlock = require('./UIExplorerBlock'); -var UIExplorerPage = require('./UIExplorerPage'); - -class TimePickerAndroidExample extends React.Component { - static title = 'TimePickerAndroid'; - static description = 'Standard Android time picker dialog'; - - state = { - isoFormatText: 'pick a time (24-hour format)', - presetHour: 4, - presetMinute: 4, - presetText: 'pick a time, default: 4:04AM', - simpleText: 'pick a time', - }; - - showPicker = async (stateKey, options) => { - try { - const {action, minute, hour} = await TimePickerAndroid.open(options); - var newState = {}; - if (action === TimePickerAndroid.timeSetAction) { - newState[stateKey + 'Text'] = _formatTime(hour, minute); - newState[stateKey + 'Hour'] = hour; - newState[stateKey + 'Minute'] = minute; - } else if (action === TimePickerAndroid.dismissedAction) { - newState[stateKey + 'Text'] = 'dismissed'; - } - this.setState(newState); - } catch ({code, message}) { - console.warn(`Error in example '${stateKey}': `, message); - } - }; - - render() { - return ( - <UIExplorerPage title="TimePickerAndroid"> - <UIExplorerBlock title="Simple time picker"> - <TouchableWithoutFeedback - onPress={this.showPicker.bind(this, 'simple', {})}> - <Text style={styles.text}>{this.state.simpleText}</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Time picker with pre-set time"> - <TouchableWithoutFeedback - onPress={this.showPicker.bind(this, 'preset', { - hour: this.state.presetHour, - minute: this.state.presetMinute, - })}> - <Text style={styles.text}>{this.state.presetText}</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - - <UIExplorerBlock title="Time picker with 24-hour time format"> - <TouchableWithoutFeedback - onPress={this.showPicker.bind(this, 'isoFormat', { - hour: this.state.isoFormatHour, - minute: this.state.isoFormatMinute, - is24Hour: true, - })}> - <Text style={styles.text}>{this.state.isoFormatText}</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - </UIExplorerPage> - ); - } -} - -/** - * Returns e.g. '3:05'. - */ -function _formatTime(hour, minute) { - return hour + ':' + (minute < 10 ? '0' + minute : minute); -} - -var styles = StyleSheet.create({ - text: { - color: 'black', - }, -}); - -module.exports = TimePickerAndroidExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/timers.html b/docs/timers.html index 08a21b93dad..c8e816392a4 100644 --- a/docs/timers.html +++ b/docs/timers.html @@ -1,4 +1,4 @@ -Timers

    Timers #

    Timers are an important part of an application and React Native implements the browser timers.

    Timers #

    • setTimeout, clearTimeout
    • setInterval, clearInterval
    • setImmediate, clearImmediate
    • requestAnimationFrame, cancelAnimationFrame

    requestAnimationFrame(fn) is not the same as setTimeout(fn, 0) - the former will fire after all the frame has flushed, whereas the latter will fire as quickly as possible (over 1000x per second on a iPhone 5S).

    setImmediate is executed at the end of the current JavaScript execution block, right before sending the batched response back to native. Note that if you call setImmediate within a setImmediate callback, it will be executed right away, it won't yield back to native in between.

    The Promise implementation uses setImmediate as its asynchronicity primitive.

    InteractionManager #

    One reason why well-built native apps feel so smooth is by avoiding expensive operations during interactions and animations. In React Native, we currently have a limitation that there is only a single JS execution thread, but you can use InteractionManager to make sure long-running work is scheduled to start after any interactions/animations have completed.

    Applications can schedule tasks to run after interactions with the following:

    InteractionManager.runAfterInteractions(() => { +Timers

    Timers #

    Timers are an important part of an application and React Native implements the browser timers.

    Timers #

    • setTimeout, clearTimeout
    • setInterval, clearInterval
    • setImmediate, clearImmediate
    • requestAnimationFrame, cancelAnimationFrame

    requestAnimationFrame(fn) is not the same as setTimeout(fn, 0) - the former will fire after all the frame has flushed, whereas the latter will fire as quickly as possible (over 1000x per second on a iPhone 5S).

    setImmediate is executed at the end of the current JavaScript execution block, right before sending the batched response back to native. Note that if you call setImmediate within a setImmediate callback, it will be executed right away, it won't yield back to native in between.

    The Promise implementation uses setImmediate as its asynchronicity primitive.

    InteractionManager #

    One reason why well-built native apps feel so smooth is by avoiding expensive operations during interactions and animations. In React Native, we currently have a limitation that there is only a single JS execution thread, but you can use InteractionManager to make sure long-running work is scheduled to start after any interactions/animations have completed.

    Applications can schedule tasks to run after interactions with the following:

    InteractionManager.runAfterInteractions(() => { // ...long-running synchronous task... });

    Compare this to other scheduling alternatives:

    • requestAnimationFrame(): for code that animates a view over time.
    • setImmediate/setTimeout/setInterval(): run code later, note this may delay animations.
    • runAfterInteractions(): run code later, without delaying active animations.

    The touch handling system considers one or more active touches to be an 'interaction' and will delay runAfterInteractions() callbacks until all touches have ended or been cancelled.

    InteractionManager also allows applications to register animations by creating an interaction 'handle' on animation start, and clearing it upon completion:

    var handle = InteractionManager.createInteractionHandle(); // run animation... (`runAfterInteractions` tasks are queued) @@ -30,6 +30,6 @@ apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/toastandroid.html b/docs/toastandroid.html index 959d93d1879..a23d86cbc32 100644 --- a/docs/toastandroid.html +++ b/docs/toastandroid.html @@ -1,90 +1,7 @@ -ToastAndroid

    ToastAndroid #

    This exposes the native ToastAndroid module as a JS module. This has a function 'show' +ToastAndroid

    ToastAndroid #

    This exposes the native ToastAndroid module as a JS module. This has a function 'show' which takes the following parameters:

    1. String message: A string with the text to toast
    2. int duration: The duration of the toast. May be ToastAndroid.SHORT or ToastAndroid.LONG

    There is also a function showWithGravity to specify the layout gravity. May be ToastAndroid.TOP, ToastAndroid.BOTTOM, ToastAndroid.CENTER.

    Basic usage:

    ToastAndroid.show('A pikachu appeared nearby !', ToastAndroid.SHORT); -ToastAndroid.showWithGravity('All Your Base Are Belong To Us', ToastAndroid.SHORT, ToastAndroid.CENTER);

    Methods #

    static show(message, duration) #

    static showWithGravity(message, duration, gravity) #

    Properties #

    SHORT: MemberExpression #

    // Toast duration constants

    LONG: MemberExpression #

    TOP: MemberExpression #

    // Toast gravity constants

    BOTTOM: MemberExpression #

    CENTER: MemberExpression #

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - StyleSheet, - Text, - ToastAndroid, - TouchableWithoutFeedback, -} = ReactNative; - -var UIExplorerBlock = require('UIExplorerBlock'); -var UIExplorerPage = require('UIExplorerPage'); - -class ToastExample extends React.Component { - static title = 'Toast Example'; - static description = 'Example that demonstrates the use of an Android Toast to provide feedback.'; - state = {}; - - render() { - return ( - <UIExplorerPage title="ToastAndroid"> - <UIExplorerBlock title="Simple toast"> - <TouchableWithoutFeedback - onPress={() => - ToastAndroid.show('This is a toast with short duration', ToastAndroid.SHORT)}> - <Text style={styles.text}>Click me.</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Toast with long duration"> - <TouchableWithoutFeedback - onPress={() => - ToastAndroid.show('This is a toast with long duration', ToastAndroid.LONG)}> - <Text style={styles.text}>Click me.</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Toast with top gravity"> - <TouchableWithoutFeedback - onPress={() => - ToastAndroid.showWithGravity( - 'This is a toast with top gravity', - ToastAndroid.SHORT, - ToastAndroid.TOP, - ) - }> - <Text style={styles.text}>Click me.</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Toast with center gravity"> - <TouchableWithoutFeedback - onPress={() => - ToastAndroid.showWithGravity( - 'This is a toast with center gravity', - ToastAndroid.SHORT, - ToastAndroid.CENTER, - ) - }> - <Text style={styles.text}>Click me.</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - <UIExplorerBlock title="Toast with bottom gravity"> - <TouchableWithoutFeedback - onPress={() => - ToastAndroid.showWithGravity( - 'This is a toast with bottom gravity', - ToastAndroid.SHORT, - ToastAndroid.BOTTOM, - ) - }> - <Text style={styles.text}>Click me.</Text> - </TouchableWithoutFeedback> - </UIExplorerBlock> - </UIExplorerPage> - ); - } -} - -var styles = StyleSheet.create({ - text: { - color: 'black', - }, -}); - -module.exports = ToastExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/toolbarandroid.html b/docs/toolbarandroid.html index 19d84fd3827..9e4e024cb27 100644 --- a/docs/toolbarandroid.html +++ b/docs/toolbarandroid.html @@ -1,4 +1,4 @@ -ToolbarAndroid

    ToolbarAndroid #

    React component that wraps the Android-only Toolbar widget. A Toolbar can display a logo, +ToolbarAndroid

    ToolbarAndroid #

    React component that wraps the Android-only Toolbar widget. A Toolbar can display a logo, navigation icon (e.g. hamburger menu), a title & subtitle and a list of actions. The title and subtitle are expanded so the logo and navigation icons are displayed on the left, title and subtitle in the middle and the actions on the right.

    If the toolbar has an only child, it will be displayed between the title and actions.

    Although the Toolbar supports remote images for the logo, navigation and action icons, this @@ -18,167 +18,25 @@ onActionSelected: if (position === 0) { // index of 'Settings' showSettings(); } -}

    Props #

    actions?: [{title: string, icon: optionalImageSource, show: enum('always', 'ifRoom', 'never'), showWithText: bool}] #

    Sets possible actions on the toolbar as part of the action menu. These are displayed as icons +}

    Props #

    actions?: PropTypes.arrayOf(PropTypes.shape({ + title: PropTypes.string.isRequired, + icon: optionalImageSource, + show: PropTypes.oneOf(['always', 'ifRoom', 'never']), + showWithText: PropTypes.bool +})) #

    Sets possible actions on the toolbar as part of the action menu. These are displayed as icons or text on the right side of the widget. If they don't fit they are placed in an 'overflow' menu.

    This property takes an array of objects, where each object has the following keys:

    • title: required, the title of this action
    • icon: the icon for this action, e.g. require('./some_icon.png')
    • show: when to show this action as an icon or hide it in the overflow menu: always, -ifRoom or never
    • showWithText: boolean, whether to show text alongside the icon or not

    contentInsetEnd?: number #

    Sets the content inset for the toolbar ending edge.

    The content inset affects the valid area for Toolbar content other than +ifRoom or never

  • showWithText: boolean, whether to show text alongside the icon or not
  • contentInsetEnd?: PropTypes.number #

    Sets the content inset for the toolbar ending edge.

    The content inset affects the valid area for Toolbar content other than the navigation button and menu. Insets define the minimum margin for these components and can be used to effectively align Toolbar content -along well-known gridlines.

    contentInsetStart?: number #

    Sets the content inset for the toolbar starting edge.

    The content inset affects the valid area for Toolbar content other than +along well-known gridlines.

    contentInsetStart?: PropTypes.number #

    Sets the content inset for the toolbar starting edge.

    The content inset affects the valid area for Toolbar content other than the navigation button and menu. Insets define the minimum margin for these components and can be used to effectively align Toolbar content -along well-known gridlines.

    logo?: optionalImageSource #

    Sets the toolbar logo.

    navIcon?: optionalImageSource #

    Sets the navigation icon.

    onActionSelected?: function #

    Callback that is called when an action is selected. The only argument that is passed to the -callback is the position of the action in the actions array.

    onIconClicked?: function #

    Callback called when the icon is selected.

    overflowIcon?: optionalImageSource #

    Sets the overflow icon.

    rtl?: bool #

    Used to set the toolbar direction to RTL. +along well-known gridlines.

    logo?: optionalImageSource #

    Sets the toolbar logo.

    navIcon?: optionalImageSource #

    Sets the navigation icon.

    onActionSelected?: PropTypes.func #

    Callback that is called when an action is selected. The only argument that is passed to the +callback is the position of the action in the actions array.

    onIconClicked?: PropTypes.func #

    Callback called when the icon is selected.

    overflowIcon?: optionalImageSource #

    Sets the overflow icon.

    rtl?: PropTypes.bool #

    Used to set the toolbar direction to RTL. In addition to this property you need to add

    android:supportsRtl="true"

    to your application AndroidManifest.xml and then call setLayoutDirection(LayoutDirection.RTL) in your MainActivity -onCreate method.

    subtitle?: string #

    Sets the toolbar subtitle.

    subtitleColor?: color #

    Sets the toolbar subtitle color.

    testID?: string #

    Used to locate this view in end-to-end tests.

    title?: string #

    Sets the toolbar title.

    titleColor?: color #

    Sets the toolbar title color.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); - -var nativeImageSource = require('nativeImageSource'); -var { - StyleSheet, - Text, - View, -} = ReactNative; -var UIExplorerBlock = require('./UIExplorerBlock'); -var UIExplorerPage = require('./UIExplorerPage'); - -var Switch = require('Switch'); -var ToolbarAndroid = require('ToolbarAndroid'); - -class ToolbarAndroidExample extends React.Component { - static title = '<ToolbarAndroid>'; - static description = 'Examples of using the Android toolbar.'; - - state = { - actionText: 'Example app with toolbar component', - toolbarSwitch: false, - colorProps: { - titleColor: '#3b5998', - subtitleColor: '#6a7180', - }, - }; - - render() { - return ( - <UIExplorerPage title="<ToolbarAndroid>"> - <UIExplorerBlock title="Toolbar with title/subtitle and actions"> - <ToolbarAndroid - actions={toolbarActions} - navIcon={nativeImageSource({ - android: 'ic_menu_black_24dp', - width: 48, - height: 48 - })} - onActionSelected={this._onActionSelected} - onIconClicked={() => this.setState({actionText: 'Icon clicked'})} - style={styles.toolbar} - subtitle={this.state.actionText} - title="Toolbar" /> - <Text>{this.state.actionText}</Text> - </UIExplorerBlock> - <UIExplorerBlock title="Toolbar with logo & custom title view (a View with Switch+Text)"> - <ToolbarAndroid - logo={nativeImageSource({ - android: 'launcher_icon', - width: 132, - height: 144 - })} - style={styles.toolbar}> - <View style={{height: 56, flexDirection: 'row', alignItems: 'center'}}> - <Switch - value={this.state.toolbarSwitch} - onValueChange={(value) => this.setState({'toolbarSwitch': value})} /> - <Text>{'\'Tis but a switch'}</Text> - </View> - </ToolbarAndroid> - </UIExplorerBlock> - <UIExplorerBlock title="Toolbar with no icon"> - <ToolbarAndroid - actions={toolbarActions} - style={styles.toolbar} - subtitle="There be no icon here" /> - </UIExplorerBlock> - <UIExplorerBlock title="Toolbar with navIcon & logo, no title"> - <ToolbarAndroid - actions={toolbarActions} - logo={nativeImageSource({ - android: 'launcher_icon', - width: 132, - height: 144 - })} - navIcon={nativeImageSource({ - android: 'ic_menu_black_24dp', - width: 48, - height: 48 - })} - style={styles.toolbar} /> - </UIExplorerBlock> - <UIExplorerBlock title="Toolbar with custom title colors"> - <ToolbarAndroid - navIcon={nativeImageSource({ - android: 'ic_menu_black_24dp', - width: 48, - height: 48 - })} - onIconClicked={() => this.setState({colorProps: {}})} - title="Wow, such toolbar" - style={styles.toolbar} - subtitle="Much native" - {...this.state.colorProps} /> - <Text> - Touch the icon to reset the custom colors to the default (theme-provided) ones. - </Text> - </UIExplorerBlock> - <UIExplorerBlock title="Toolbar with remote logo & navIcon"> - <ToolbarAndroid - actions={[{title: 'Bunny', icon: require('./bunny.png'), show: 'always'}]} - logo={require('./hawk.png')} - navIcon={require('./bunny.png')} - title="Bunny and Hawk" - style={styles.toolbar} /> - </UIExplorerBlock> - <UIExplorerBlock title="Toolbar with custom overflowIcon"> - <ToolbarAndroid - actions={toolbarActions} - overflowIcon={require('./bunny.png')} - style={styles.toolbar} /> - </UIExplorerBlock> - </UIExplorerPage> - ); - } - - _onActionSelected = (position) => { - this.setState({ - actionText: 'Selected ' + toolbarActions[position].title, - }); - }; -} - -var toolbarActions = [ - {title: 'Create', icon: nativeImageSource({ - android: 'ic_create_black_48dp', - width: 96, - height: 96 - }), show: 'always'}, - {title: 'Filter'}, - {title: 'Settings', icon: nativeImageSource({ - android: 'ic_settings_black_48dp', - width: 96, - height: 96 - }), show: 'always'}, -]; - -var styles = StyleSheet.create({ - toolbar: { - backgroundColor: '#e9eaed', - height: 56, - }, -}); - -module.exports = ToolbarAndroidExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/touchablehighlight.html b/docs/touchablehighlight.html index 5bffe1af17b..ca50c2279b6 100644 --- a/docs/touchablehighlight.html +++ b/docs/touchablehighlight.html @@ -1,4 +1,4 @@ -TouchableHighlight

    TouchableHighlight #

    A wrapper for making views respond properly to touches. +TouchableHighlight

    TouchableHighlight #

    A wrapper for making views respond properly to touches. On press down, the opacity of the wrapped view is decreased, which allows the underlay color to show through, darkening or tinting the view.

    The underlay comes from wrapping the child in a new View, which can affect layout, and sometimes cause unwanted visual artifacts if not used correctly, @@ -13,9 +13,9 @@ If you wish to have several child components, wrap them in a View.

    Example /> </TouchableHighlight> ); -},

    Props #

    activeOpacity?: number #

    Determines what the opacity of the wrapped view should be when touch is -active.

    onHideUnderlay?: function #

    Called immediately after the underlay is hidden

    onShowUnderlay?: function #

    Called immediately after the underlay is shown

    style?: ViewPropTypes.style #

    underlayColor?: color #

    The color of the underlay that will show through when the touch is -active.

    ioshasTVPreferredFocus?: bool #

    (Apple TV only) TV preferred focus (see documentation for the View component).

    iostvParallaxProperties?: object #

    (Apple TV only) Object with properties to control Apple TV parallax effects.

    enabled: If true, parallax effects are enabled. Defaults to true. +},

    Props #

    activeOpacity?: PropTypes.number #

    Determines what the opacity of the wrapped view should be when touch is +active.

    onHideUnderlay?: PropTypes.func #

    Called immediately after the underlay is hidden

    onShowUnderlay?: PropTypes.func #

    Called immediately after the underlay is shown

    style?: ViewPropTypes.style #

    underlayColor?: color #

    The color of the underlay that will show through when the touch is +active.

    ioshasTVPreferredFocus?: PropTypes.bool #

    (Apple TV only) TV preferred focus (see documentation for the View component).

    iostvParallaxProperties?: PropTypes.object #

    (Apple TV only) Object with properties to control Apple TV parallax effects.

    enabled: If true, parallax effects are enabled. Defaults to true. shiftDistanceX: Defaults to 2.0. shiftDistanceY: Defaults to 2.0. tiltAngle: Defaults to 0.05. @@ -35,6 +35,6 @@ magnification: Defaults to 1.0.

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/touchablenativefeedback.html b/docs/touchablenativefeedback.html index c6099109c40..ccab2ed7962 100644 --- a/docs/touchablenativefeedback.html +++ b/docs/touchablenativefeedback.html @@ -1,4 +1,4 @@ -TouchableNativeFeedback

    TouchableNativeFeedback #

    A wrapper for making views respond properly to touches (Android only). +TouchableNativeFeedback

    TouchableNativeFeedback #

    A wrapper for making views respond properly to touches (Android only). On Android this component uses native state drawable to display touch feedback.

    At the moment it only supports having a single View instance as a child node, as it's implemented by replacing that View with another instance of @@ -16,7 +16,7 @@ RCTView node with some additional properties set.

    Background drawable of n },

    Props #

    background?: backgroundPropType #

    Determines the type of background drawable that's going to be used to display feedback. It takes an object with type property and extra data depending on the type. It's recommended to use one of the static -methods to generate that dictionary.

    useForeground?: bool #

    Set to true to add the ripple effect to the foreground of the view, instead of the +methods to generate that dictionary.

    useForeground?: PropTypes.bool #

    Set to true to add the ripple effect to the foreground of the view, instead of the background. This is useful if one of your child views has a background of its own, or you're e.g. displaying images, and you don't want the ripple to be covered by them.

    Check TouchableNativeFeedback.canUseNativeForeground() first, as this is only available on Android 6.0 and above. If you try to use this on older versions you will get a warning and @@ -43,6 +43,6 @@ API level 21+.

    Parameters:< apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/touchableopacity.html b/docs/touchableopacity.html index 0b3d510d03a..f2ac6620d65 100644 --- a/docs/touchableopacity.html +++ b/docs/touchableopacity.html @@ -1,4 +1,4 @@ -TouchableOpacity

    TouchableOpacity #

    A wrapper for making views respond properly to touches. +TouchableOpacity

    TouchableOpacity #

    A wrapper for making views respond properly to touches. On press down, the opacity of the wrapped view is decreased, dimming it.

    Opacity is controlled by wrapping the children in an Animated.View, which is added to the view hiearchy. Be aware that this can affect layout.

    Example:

    renderButton: function() { return ( @@ -9,8 +9,8 @@ added to the view hiearchy. Be aware that this can affect layout.

    Example /> </TouchableOpacity> ); -},

    Props #

    activeOpacity?: number #

    Determines what the opacity of the wrapped view should be when touch is -active. Defaults to 0.2.

    focusedOpacity?: number #

    tvParallaxProperties?: object #

    Apple TV parallax effects

    Methods #

    setOpacityTo(value: number, duration: number) #

    Animate the touchable to a new opacity.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/touchablewithoutfeedback.html b/docs/touchablewithoutfeedback.html index a635cb09d13..b784f2c31c2 100644 --- a/docs/touchablewithoutfeedback.html +++ b/docs/touchablewithoutfeedback.html @@ -1,12 +1,17 @@ -TouchableWithoutFeedback

    TouchableWithoutFeedback #

    Do not use unless you have a very good reason. All the elements that +TouchableWithoutFeedback

    TouchableWithoutFeedback #

    Do not use unless you have a very good reason. All elements that respond to press should have a visual feedback when touched.

    TouchableWithoutFeedback supports only one child. -If you wish to have several child components, wrap them in a View.

    Props #

    accessibilityComponentType?: AccessibilityComponentTypes #

    accessibilityTraits?: AccessibilityTraits, [AccessibilityTraits] #

    accessible?: bool #

    delayLongPress?: number #

    Delay in ms, from onPressIn, before onLongPress is called.

    delayPressIn?: number #

    Delay in ms, from the start of the touch, before onPressIn is called.

    delayPressOut?: number #

    Delay in ms, from the release of the touch, before onPressOut is called.

    disabled?: bool #

    If true, disable all interactions for this component.

    hitSlop?: {top: number, left: number, bottom: number, right: number} #

    This defines how far your touch can start away from the button. This is +If you wish to have several child components, wrap them in a View.

    Props #

    accessibilityComponentType?: PropTypes.oneOf( + AccessibilityComponentTypes +) #

    accessibilityTraits?: PropTypes.oneOfType([ + PropTypes.oneOf(AccessibilityTraits), + PropTypes.arrayOf(PropTypes.oneOf(AccessibilityTraits)), +]) #

    accessible?: PropTypes.bool #

    delayLongPress?: PropTypes.number #

    Delay in ms, from onPressIn, before onLongPress is called.

    delayPressIn?: PropTypes.number #

    Delay in ms, from the start of the touch, before onPressIn is called.

    delayPressOut?: PropTypes.number #

    Delay in ms, from the release of the touch, before onPressOut is called.

    disabled?: PropTypes.bool #

    If true, disable all interactions for this component.

    hitSlop?: {top: number, left: number, bottom: number, right: number} #

    This defines how far your touch can start away from the button. This is added to pressRetentionOffset when moving off of the button. NOTE The touch area never extends past the parent view bounds and the Z-index of sibling views always takes precedence if a touch hits two overlapping -views.

    onLayout?: function #

    Invoked on mount and layout changes with

    {nativeEvent: {layout: {x, y, width, height}}}

    onLongPress?: function #

    onPress?: function #

    Called when the touch is released, but not if cancelled (e.g. by a scroll -that steals the responder lock).

    onPressIn?: function #

    onPressOut?: function #

    pressRetentionOffset?: {top: number, left: number, bottom: number, right: number} #

    When the scroll view is disabled, this defines how far your touch may +views.

    onLayout?: PropTypes.func #

    Invoked on mount and layout changes with

    {nativeEvent: {layout: {x, y, width, height}}}

    onLongPress?: PropTypes.func #

    onPress?: PropTypes.func #

    Called when the touch is released, but not if cancelled (e.g. by a scroll +that steals the responder lock).

    onPressIn?: PropTypes.func #

    onPressOut?: PropTypes.func #

    pressRetentionOffset?: {top: number, left: number, bottom: number, right: number} #

    When the scroll view is disabled, this defines how far your touch may move off of the button, before deactivating the button. Once deactivated, try moving it back and you'll see that the button is once again reactivated! Move it back and forth several times while the scroll view @@ -26,6 +31,6 @@ is disabled. Ensure you pass in a constant to reduce memory allocations.

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/transforms.html b/docs/transforms.html index d825b49a548..8968fc121ba 100644 --- a/docs/transforms.html +++ b/docs/transforms.html @@ -1,4 +1,4 @@ -Transforms

    Transforms #

    Props #

    decomposedMatrix?: DecomposedMatrixPropType #

    transform?: [{perspective: number}, {rotate: string}, {rotateX: string}, {rotateY: string}, {rotateZ: string}, {scale: number}, {scaleX: number}, {scaleY: number}, {translateX: number}, {translateY: number}, {skewX: string}, {skewY: string}] #

    transformMatrix?: TransformMatrixPropType #

    You can edit the content above on GitHub and send us a pull request!

    Transforms #

    Props #

    decomposedMatrix?: DecomposedMatrixPropType #

    transform?: [{perspective: number}, {rotate: string}, {rotateX: string}, {rotateY: string}, {rotateZ: string}, {scale: number}, {scaleX: number}, {scaleY: number}, {translateX: number}, {translateY: number}, {skewX: string}, {skewY: string}] #

    transformMatrix?: TransformMatrixPropType #

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/troubleshooting.html b/docs/troubleshooting.html index 70be8553b9c..ea95e412447 100644 --- a/docs/troubleshooting.html +++ b/docs/troubleshooting.html @@ -1,4 +1,4 @@ -Troubleshooting

    Troubleshooting #

    These are some common issues you may run into while setting up React Native. If you encounter something that is not listed here, try searching for the issue in GitHub.

    Port already in use #

    The React Native packager runs on port 8081. If another process is already using that port (such as McAfee Antivirus on Windows), you can either terminate that process, or change the port that the packager uses.

    Terminating a process on port 8081 #

    Run the following command on a Mac to find the id for the process that is listening on port 8081:

    $ sudo lsof -i :8081

    Then run the following to terminate the process:

    $ kill -9 <PID>

    On Windows you can find the process using port 8081 using Resource Monitor and stop it using Task Manager.

    Using a port other than 8081 #

    You can configure the packager to use a port other than 8081 by using the port parameter:

    $ react-native start --port=8088

    You will also need to update your applications to load the JavaScript bundle from the new port. Open the in-app Developer menu, then go to Dev SettingsDebug server host for device and replace 8081 with your port of choice.

    NPM locking error #

    If you encounter an error such as npm WARN locking Error: EACCES while using the React Native CLI, try running the following:

    sudo chown -R $USER ~/.npm +Troubleshooting

    Troubleshooting #

    These are some common issues you may run into while setting up React Native. If you encounter something that is not listed here, try searching for the issue in GitHub.

    Port already in use #

    The React Native packager runs on port 8081. If another process is already using that port, you can either terminate that process, or change the port that the packager uses.

    Terminating a process on port 8081 #

    Run the following command on a Mac to find the id for the process that is listening on port 8081:

    $ sudo lsof -i :8081

    Then run the following to terminate the process:

    $ kill -9 <PID>

    On Windows you can find the process using port 8081 using Resource Monitor and stop it using Task Manager.

    Using a port other than 8081 #

    You can configure the packager to use a port other than 8081 by using the port parameter:

    $ react-native start --port=8088

    You will also need to update your applications to load the JavaScript bundle from the new port.

    NPM locking error #

    If you encounter an error such as npm WARN locking Error: EACCES while using the React Native CLI, try running the following:

    sudo chown -R $USER ~/.npm sudo chown -R $USER /usr/local/lib/node_modules

    Missing libraries for React #

    If you added React Native manually to your project, make sure you have included all the relevant dependencies that you are using, like RCTText.xcodeproj, RCTImage.xcodeproj. Next, the binaries built by these dependencies have to be linked to your app binary. Use the Linked Frameworks and Binaries section in the Xcode project settings. More detailed steps are here: Linking Libraries.

    If you are using CocoaPods, verify that you have added React along with the subspecs to the Podfile. For example, if you were using the <Text />, <Image /> and fetch() APIs, you would need to add these in your Podfile:

    pod 'React', :path => '../node_modules/react-native', :subspecs => [ 'RCTText', 'RCTImage', @@ -22,6 +22,6 @@ import Firebase from 'firebase' \ No newline at end of file + \ No newline at end of file diff --git a/docs/tutorial.html b/docs/tutorial.html index 7516e35d38b..9ec167226f4 100644 --- a/docs/tutorial.html +++ b/docs/tutorial.html @@ -1,17 +1,18 @@ -Tutorial

    Tutorial #

    React Native is like React, but it uses native components instead of web components as building blocks. So to understand the basic structure of a React Native app, you need to understand some of the basic React concepts, like JSX, components, state, and props. If you already know React, you still need to learn some React-Native-specific stuff, like the native components. This +Tutorial

    Tutorial #

    React Native is like React, but it uses native components instead of web components as building blocks. So to understand the basic structure of a React Native app, you need to understand some of the basic React concepts, like JSX, components, state, and props. If you already know React, you still need to learn some React-Native-specific stuff, like the native components. This tutorial is aimed at all audiences, whether you have React experience or not.

    Let's do this thing.

    Hello World #

    In accordance with the ancient traditions of our people, we must first build an app that does nothing except say "Hello world". Here it is:

    import React, { Component } from 'react'; import { AppRegistry, Text } from 'react-native'; -class HelloWorldApp extends Component { +export default class HelloWorldApp extends Component { render() { return ( <Text>Hello world!</Text> ); } } - -AppRegistry.registerComponent('HelloWorldApp', () => HelloWorldApp);

    If you are feeling curious, you can play around with sample code directly in the web simulators. You can also paste it into your index.ios.js or index.android.js file to create a real app on your local machine.

    What's going on here? #

    Some of the things in here might not look like JavaScript to you. Don't panic. This is the future.

    First of all, ES2015 (also known as ES6) is a set of improvements to JavaScript that is now part of the official standard, but not yet supported by all browsers, so often it isn't used yet in web development. React Native ships with ES2015 support, so you can use this stuff without worrying about compatibility. import, from, class, extends, and the () => syntax in the example above are all ES2015 features. If you aren't familiar with ES2015, you can probably pick it up just by reading through sample code like this tutorial has. If you want, this page has a good overview of ES2015 features.

    The other unusual thing in this code example is <Text>Hello world!</Text>. This is JSX - a syntax for embedding XML within JavaScript. Many frameworks use a special templating language which lets you embed code inside markup language. In React, this is reversed. JSX lets you write your markup language inside code. It looks like HTML on the web, except instead of web things like <div> or <span>, you use React components. In this case, <Text> -is a built-in component that just displays some text.

    Component and AppRegistry #

    So this code is defining HelloWorldApp, a new Component, and it's registering it with the AppRegistry. When you're building a React Native app, you'll be making new components a lot. Anything you see on the screen is some sort of component. A component can be pretty simple - the only thing that's required is a render function which returns some JSX to render.

    The AppRegistry just tells React Native which component is the root one for the whole application. You won't be thinking about AppRegistry a lot - there will probably just be one call to AppRegistry.registerComponent in your whole app. It's included in these examples so you can paste the whole thing into your index.ios.js or index.android.js file and get it running.

    This App Doesn't Do Very Much #

    Good point. To make components do more interesting things, you need to learn about Props.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/understanding-cli.html b/docs/understanding-cli.html index 744891175ab..6d278795fe3 100644 --- a/docs/understanding-cli.html +++ b/docs/understanding-cli.html @@ -1,4 +1,4 @@ -Understanding the CLI

    Understanding the CLI #

    Though you may have installed the react-native-cli via npm as a separate module, it is a shell for accessing the CLI embedded +Understanding the CLI

    Understanding the CLI #

    Though you may have installed the react-native-cli via npm as a separate module, it is a shell for accessing the CLI embedded in the React Native of each project. Your commands and their effects are dependent on the version of the module of react-native in context of the project. This guide will give a brief overview of the CLI in the module.

    The local CLI #

    React Native has a local-cli folder with a file named cliEntry.js. Here, the commands are read @@ -24,6 +24,6 @@ required in commands.js, which will register it as a documented com apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/upgrading.html b/docs/upgrading.html index c8e91ac81a7..ceae3e21648 100644 --- a/docs/upgrading.html +++ b/docs/upgrading.html @@ -1,18 +1,11 @@ -Upgrading

    Upgrading #

    Upgrading to new versions of React Native will give you access to more APIs, views, developer tools -and other goodies. Because React Native projects are essentially made up of an Android project, an -iOS project and a JavaScript project, all combined under an npm package, upgrading can be rather -tricky. But we try to make it easy for you. Here's what you need to do to upgrade from an older -version of React Native:

    Upgrade based on Git #

    IMPORTANT: You don't have to install the new version of React Native, it will be installed automatically.

    The module react-native-git-upgrade provides a one-step operation to upgrade the source files with -a minimum of conflicts. Under the hood, it consists in 2 phases:

    • First, it computes a Git patch between both old and new template files,
    • Then, the patch is applied on the user's sources.

    1. Install Git #

    Your project doesn't have to be handled by the Git versioning sytem (could be Mercurial, SVN or none) -but Git has to be installed and available in the PATH. You can download Git here: -https://git-scm.com/downloads

    2. Install the react-native-git-upgrade module #

    It's a CLI tool and must be installed globally:

    $ npm install -g react-native-git-upgrade

    3. Run the command #

    Run the command to start the process:

    $ react-native-git-upgrade -# Upgrade React Native to the latest version +Upgrading to new React Native versions

    Upgrading to new React Native versions #

    Upgrading to new versions of React Native will give you access to more APIs, views, developer tools and other goodies. Upgrading requires a small amount of effort, but we try to make it easy for you. The instructions are a bit different depending on whether you used create-react-native-app or react-native init to create your project.

    Create React Native App projects #

    Upgrading your Create React Native App project to a new version of React Native requires updating the react-native, react, and expo package versions in your package.json file. Please refer to this document to find out what versions are supported. You will also need to set the correct sdkVersion in your app.json file.

    See the CRNA user guide for up-to-date information about upgrading your project.

    Projects built with native code #

    -# Or: - -$ react-native-git-upgrade X.Y.Z -# Upgrade React Native to the X.Y.Z version

    The templates are upgraded in a optimized way. You still may encounter conflicts but only where the Git -3-way merge have failed, depending on the version and how you modified your sources.

    4. Resolve the conflicts #

    Conflicted files include delimiters which make very clear where the changes come from. For example:

    13B07F951A680F5B00A75B9A /* Release */ = { +

    Because React Native projects built with native code are essentially made up of an Android project, an iOS project, and a JavaScript project, upgrading can be rather tricky. Here's what you need to do to upgrade from an older version of React Native.

    Upgrade based on Git #

    The module react-native-git-upgrade provides a one-step operation to upgrade the source files with a minimum of conflicts. Under the hood, it consists in 2 phases:

    • First, it computes a Git patch between both old and new template files,
    • Then, the patch is applied on the user's sources.

    IMPORTANT: You don't have to install the new version of the react-native package, it will be installed automatically.

    1. Install Git #

    While your project does not have to be handled by the Git versioning system -- you can use Mercurial, SVN, or nothing -- you will still need to install Git on your system in order to use react-native-git-upgrade. Git will also need to be available in the PATH.

    2. Install the react-native-git-upgrade module #

    The react-native-git-upgrade module provides a CLI and must be installed globally:

    $ npm install -g react-native-git-upgrade

    3. Run the command #

    Run the following command to start the process of upgrading to the latest version:

    $ react-native-git-upgrade

    You may specify a React Native version by passing an argument: react-native-git-upgrade X.Y

    The templates are upgraded in a optimized way. You still may encounter conflicts but only where the Git 3-way merge have failed, depending on the version and how you modified your sources.

    4. Resolve the conflicts #

    Conflicted files include delimiters which make very clear where the changes come from. For example:

    13B07F951A680F5B00A75B9A /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; @@ -31,13 +24,12 @@ $ react-native- /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../node_modules/react-native/React/**", "$(SRCROOT)/../node_modules/react-native-code-push/ios/CodePush/**", - );

    You can think of "ours" as "your team" and "theirs" as "the React Native dev team".

    Alternative #

    Use this only in case the above didn't work.

    1. Upgrade the react-native dependency #

    Note the latest version of the react-native npm package from here (or use npm info react-native to check):

    Now install that version of react-native in your project with npm install --save:

    $ npm install --save react-native@X.Y + );

    You can think of "ours" as "your team" and "theirs" as "the React Native dev team".

    Alternative #

    Use this only in case the above didn't work.

    1. Upgrade the react-native dependency #

    Note the latest version of the react-native npm package from here (or use npm info react-native to check).

    Now install that version of react-native in your project with npm install --save:

    $ npm install --save react-native@X.Y # where X.Y is the semantic version you are upgrading to npm WARN peerDependencies The peer dependency react@~R included from react-native...

    If you saw a warning about the peerDependency, also upgrade react by running:

    $ npm install --save react@R -# where R is the new version of react from the peerDependency warning you saw

    2. Upgrade your project templates #

    The new npm package may contain updates to the files that are normally generated when you +# where R is the new version of react from the peerDependency warning you saw

    2. Upgrade your project templates #

    The new npm package may contain updates to the files that are normally generated when you run react-native init, like the iOS and the Android sub-projects.

    You may consult rn-diff to see if there were changes in the project template files. -In case there weren't any, simply rebuild the project and continue developing. In case of minor changes, you may update your project manually and rebuild.

    If there were major changes, run this in a terminal to get these:

    $ react-native upgrade

    This will check your files against the latest template and perform the following:

    • If there is a new file in the template, it is simply created.
    • If a file in the template is identical to your file, it is skipped.
    • If a file is different in your project than the template, you will be prompted; you have options -to keep your file or overwrite it with the template version.

    Manual Upgrades #

    Some upgrades require manual steps, e.g. 0.13 to 0.14, or 0.28 to 0.29. Be sure to check the release notes when upgrading so that you can identify any manual changes your particular project may require.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/using-a-listview.html b/docs/using-a-listview.html index 98191fabd19..9b587c2a5f0 100644 --- a/docs/using-a-listview.html +++ b/docs/using-a-listview.html @@ -1,31 +1,84 @@ -Using a ListView

    Using a ListView #

    The ListView component displays a scrolling list of changing, but similarly structured, data.

    ListView works well for long lists of data, where the number of items might change over time. Unlike the more generic ScrollView, the ListView only renders elements that are currently showing on the screen, not all the elements at once.

    The ListView component requires two props: dataSource and renderRow. dataSource is the source of information for the list. renderRow takes one item from the source and returns a formatted component to render.

    This example creates a simple ListView of hardcoded data. It first initializes the dataSource that will be used to populate the ListView. Each item in the dataSource is then rendered as a Text component. Finally it renders the ListView and all Text components.

    A rowHasChanged function is required to use ListView. Here we just say a row has changed if the row we are on is not the same as the previous row.

    import React, { Component } from 'react'; -import { AppRegistry, ListView, Text, View } from 'react-native'; +Using List Views

    Using List Views #

    React Native provides a suite of components for presenting lists of data. Generally, you'll want to use either FlatList or SectionList.

    The FlatList component displays a scrolling list of changing, but similarly structured, data. FlatList works well for long lists of data, where the number of items might change over time. Unlike the more generic ScrollView, the FlatList only renders elements that are currently showing on the screen, not all the elements at once.

    The FlatList component requires two props: data and renderItem. data is the source of information for the list. renderItem takes one item from the source and returns a formatted component to render.

    This example creates a simple FlatList of hardcoded data. Each item in the data props is rendered as a Text component. The FlatListBasics component then renders the FlatList and all Text components.

    One of the most common uses for a ListView is displaying data that you fetch from a server. To do that, you will need to learn about networking in React Native.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/using-a-scrollview.html b/docs/using-a-scrollview.html index 2fe5350c80c..e8b53d23251 100644 --- a/docs/using-a-scrollview.html +++ b/docs/using-a-scrollview.html @@ -1,7 +1,7 @@ -Using a ScrollView

    Using a ScrollView #

    The ScrollView is a generic scrolling container that can host multiple components and views. The scrollable items need not be homogenous, and you can scroll both vertically and horizontally (by setting the horizontal property).

    This example creates a vertical ScrollView with both images and text mixed together.

    import React, { Component } from 'react'; +Using a ScrollView

    Using a ScrollView #

    The ScrollView is a generic scrolling container that can host multiple components and views. The scrollable items need not be homogenous, and you can scroll both vertically and horizontally (by setting the horizontal property).

    This example creates a vertical ScrollView with both images and text mixed together.

    import React, { Component } from 'react'; import { AppRegistry, ScrollView, Image, Text } from 'react-native' -class IScrolledDownAndWhatHappenedNextShockedMe extends Component { +export default class IScrolledDownAndWhatHappenedNextShockedMe extends Component { render() { return ( <ScrollView> @@ -40,11 +40,11 @@ class IScrolledDownAndWhatHappenedNextShockedMe); } } - - -AppRegistry.registerComponent( + +// skip these lines if using Create React Native App +AppRegistry.registerComponent( 'IScrolledDownAndWhatHappenedNextShockedMe', - () => IScrolledDownAndWhatHappenedNextShockedMe);

    ScrollView works best to present a small amount of things of a limited size. All the elements and views of a ScrollView are rendered, even if they are not currently shown on the screen. If you have a long list of more items that can fit on the screen, you should use a ListView instead. So let's learn about the ListView next.

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/vibration.html b/docs/vibration.html index 60421182a01..92bf5c0740c 100644 --- a/docs/vibration.html +++ b/docs/vibration.html @@ -1,120 +1,4 @@ -Vibration

    Vibration #

    Methods #

    static vibrate(pattern, repeat) #

    static cancel() #

    Stop vibration

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - StyleSheet, - View, - Text, - TouchableHighlight, - Vibration, - Platform, -} = ReactNative; - -exports.framework = 'React'; -exports.title = 'Vibration'; -exports.description = 'Vibration API'; - -var pattern, patternLiteral, patternDescription; -if (Platform.OS === 'android') { - pattern = [0, 500, 200, 500]; - patternLiteral = '[0, 500, 200, 500]'; - patternDescription = `${patternLiteral} -arg 0: duration to wait before turning the vibrator on. -arg with odd: vibration length. -arg with even: duration to wait before next vibration. -`; -} else { - pattern = [0, 1000, 2000, 3000]; - patternLiteral = '[0, 1000, 2000, 3000]'; - patternDescription = `${patternLiteral} -vibration length on iOS is fixed. -pattern controls durations BETWEEN each vibration only. - -arg 0: duration to wait before turning the vibrator on. -subsequent args: duration to wait before next vibrattion. -`; -} - -exports.examples = [ - { - title: 'Pattern Descriptions', - render() { - return ( - <View style={styles.wrapper}> - <Text>{patternDescription}</Text> - </View> - ); - }, - }, - { - title: 'Vibration.vibrate()', - render() { - return ( - <TouchableHighlight - style={styles.wrapper} - onPress={() => Vibration.vibrate()}> - <View style={styles.button}> - <Text>Vibrate</Text> - </View> - </TouchableHighlight> - ); - }, - }, - { - title: `Vibration.vibrate(${patternLiteral})`, - render() { - return ( - <TouchableHighlight - style={styles.wrapper} - onPress={() => Vibration.vibrate(pattern)}> - <View style={styles.button}> - <Text>Vibrate once</Text> - </View> - </TouchableHighlight> - ); - }, - }, - { - title: `Vibration.vibrate(${patternLiteral}, true)`, - render() { - return ( - <TouchableHighlight - style={styles.wrapper} - onPress={() => Vibration.vibrate(pattern, true)}> - <View style={styles.button}> - <Text>Vibrate until cancel</Text> - </View> - </TouchableHighlight> - ); - }, - }, - { - title: 'Vibration.cancel()', - render() { - return ( - <TouchableHighlight - style={styles.wrapper} - onPress={() => Vibration.cancel()}> - <View style={styles.button}> - <Text>Cancel</Text> - </View> - </TouchableHighlight> - ); - }, - }, -]; - -var styles = StyleSheet.create({ - wrapper: { - borderRadius: 5, - marginBottom: 5, - }, - button: { - backgroundColor: '#eeeeee', - padding: 10, - }, -});

    Vibration #

    Methods #

    static vibrate(pattern, repeat) #

    static cancel() #

    Stop vibration

    You can edit the content above on GitHub and send us a pull request!

    \ No newline at end of file + \ No newline at end of file diff --git a/docs/vibrationios.html b/docs/vibrationios.html index 8eafdb0c0e5..5ba6f6b28e1 100644 --- a/docs/vibrationios.html +++ b/docs/vibrationios.html @@ -1,46 +1,7 @@ -VibrationIOS

    VibrationIOS #

    NOTE: VibrationIOS is being deprecated. Use Vibration instead.

    The Vibration API is exposed at VibrationIOS.vibrate(). On iOS, calling this +VibrationIOS

    VibrationIOS #

    NOTE: VibrationIOS is being deprecated. Use Vibration instead.

    The Vibration API is exposed at VibrationIOS.vibrate(). On iOS, calling this function will trigger a one second vibration. The vibration is asynchronous so this method will return immediately.

    There will be no effect on devices that do not support Vibration, eg. the iOS -simulator.

    Vibration patterns are currently unsupported.

    Methods #

    static vibrate() #

    @deprecated

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - StyleSheet, - View, - Text, - TouchableHighlight, - VibrationIOS -} = ReactNative; - -exports.framework = 'React'; -exports.title = 'VibrationIOS'; -exports.description = 'Vibration API for iOS'; -exports.examples = [{ - title: 'VibrationIOS.vibrate()', - render() { - return ( - <TouchableHighlight - style={styles.wrapper} - onPress={() => VibrationIOS.vibrate()}> - <View style={styles.button}> - <Text>Vibrate</Text> - </View> - </TouchableHighlight> - ); - }, -}]; - -var styles = StyleSheet.create({ - wrapper: { - borderRadius: 5, - marginBottom: 5, - }, - button: { - backgroundColor: '#eeeeee', - padding: 10, - }, -});
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/view.html b/docs/view.html index a30169cce61..dbdc0c47c0f 100644 --- a/docs/view.html +++ b/docs/view.html @@ -1,4 +1,4 @@ -View

    View #

    The most fundamental component for building a UI, View is a container that supports layout with +View

    View #

    The most fundamental component for building a UI, View is a container that supports layout with flexbox, style, some touch handling, and accessibility controls. View maps directly to the @@ -81,7 +81,7 @@ fires accessibility events and if it is reported to accessibility services that query the screen. Works for Android only.

    Possible values:

    • 'auto' - The system determines whether the view is important for accessibility - default (recommended).
    • 'yes' - The view is important for accessibility.
    • 'no' - The view is not important for accessibility.
    • 'no-hide-descendants' - The view is not important for accessibility, nor are any of its descendant views.

    See the Android importantForAccessibility docs -for reference.

    androidneedsOffscreenAlphaCompositing?: bool #

    Whether this View needs to rendered offscreen and composited with an alpha +for reference.

    androidnativeID?: string #

    Used to locate this view from native classes.

    This disables the 'layout-only view removal' optimization for this view!

    androidneedsOffscreenAlphaCompositing?: bool #

    Whether this View needs to rendered offscreen and composited with an alpha in order to preserve 100% correct colors and blending behavior. The default (false) falls back to drawing the component and its children with an alpha applied to the paint used to draw each element instead of rendering the full @@ -112,236 +112,7 @@ modify this component's dimensions nor its children; for example, when translating the position of a static view, rasterization allows the renderer to reuse a cached bitmap of a static view and quickly composite it during each frame.

    Rasterization incurs an off-screen drawing pass and the bitmap consumes -memory. Test and measure when using this property.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - StyleSheet, - Text, - View, -} = ReactNative; -var TouchableWithoutFeedback = require('TouchableWithoutFeedback'); - -var styles = StyleSheet.create({ - box: { - backgroundColor: '#527FE4', - borderColor: '#000033', - borderWidth: 1, - }, - zIndex: { - justifyContent: 'space-around', - width: 100, - height: 50, - marginTop: -10, - }, -}); - -class ViewBorderStyleExample extends React.Component { - state = { - showBorder: true - }; - - render() { - return ( - <TouchableWithoutFeedback onPress={this._handlePress}> - <View> - <View style={{ - borderWidth: 1, - borderStyle: this.state.showBorder ? 'dashed' : null, - padding: 5 - }}> - <Text style={{fontSize: 11}}> - Dashed border style - </Text> - </View> - <View style={{ - marginTop: 5, - borderWidth: 1, - borderRadius: 5, - borderStyle: this.state.showBorder ? 'dotted' : null, - padding: 5 - }}> - <Text style={{fontSize: 11}}> - Dotted border style - </Text> - </View> - </View> - </TouchableWithoutFeedback> - ); - } - - _handlePress = () => { - this.setState({showBorder: !this.state.showBorder}); - }; -} - -class ZIndexExample extends React.Component { - state = { - flipped: false - }; - - render() { - const indices = this.state.flipped ? [-1, 0, 1, 2] : [2, 1, 0, -1]; - return ( - <TouchableWithoutFeedback onPress={this._handlePress}> - <View> - <Text style={{paddingBottom: 10}}>Tap to flip sorting order</Text> - <View style={[ - styles.zIndex, - {marginTop: 0, backgroundColor: '#E57373', zIndex: indices[0]} - ]}> - <Text>ZIndex {indices[0]}</Text> - </View> - <View style={[ - styles.zIndex, - {marginLeft: 50, backgroundColor: '#FFF176', zIndex: indices[1]} - ]}> - <Text>ZIndex {indices[1]}</Text> - </View> - <View style={[ - styles.zIndex, - {marginLeft: 100, backgroundColor: '#81C784', zIndex: indices[2]} - ]}> - <Text>ZIndex {indices[2]}</Text> - </View> - <View style={[ - styles.zIndex, - {marginLeft: 150, backgroundColor: '#64B5F6', zIndex: indices[3]} - ]}> - <Text>ZIndex {indices[3]}</Text> - </View> - </View> - </TouchableWithoutFeedback> - ); - } - - _handlePress = () => { - this.setState({flipped: !this.state.flipped}); - }; -} - -exports.title = '<View>'; -exports.description = 'Basic building block of all UI, examples that ' + - 'demonstrate some of the many styles available.'; - -exports.displayName = 'ViewExample'; -exports.examples = [ - { - title: 'Background Color', - render: function() { - return ( - <View style={{backgroundColor: '#527FE4', padding: 5}}> - <Text style={{fontSize: 11}}> - Blue background - </Text> - </View> - ); - }, - }, { - title: 'Border', - render: function() { - return ( - <View style={{borderColor: '#527FE4', borderWidth: 5, padding: 10}}> - <Text style={{fontSize: 11}}>5px blue border</Text> - </View> - ); - }, - }, { - title: 'Padding/Margin', - render: function() { - return ( - <View style={{borderColor: '#bb0000', borderWidth: 0.5}}> - <View style={[styles.box, {padding: 5}]}> - <Text style={{fontSize: 11}}>5px padding</Text> - </View> - <View style={[styles.box, {margin: 5}]}> - <Text style={{fontSize: 11}}>5px margin</Text> - </View> - <View style={[styles.box, {margin: 5, padding: 5, alignSelf: 'flex-start'}]}> - <Text style={{fontSize: 11}}> - 5px margin and padding, - </Text> - <Text style={{fontSize: 11}}> - widthAutonomous=true - </Text> - </View> - </View> - ); - }, - }, { - title: 'Border Radius', - render: function() { - return ( - <View style={{borderWidth: 0.5, borderRadius: 5, padding: 5}}> - <Text style={{fontSize: 11}}> - Too much use of `borderRadius` (especially large radii) on - anything which is scrolling may result in dropped frames. - Use sparingly. - </Text> - </View> - ); - }, - }, { - title: 'Border Style', - render: function() { - return <ViewBorderStyleExample />; - }, - }, { - title: 'Circle with Border Radius', - render: function() { - return ( - <View style={{borderRadius: 10, borderWidth: 1, width: 20, height: 20}} /> - ); - }, - }, { - title: 'Overflow', - render: function() { - return ( - <View style={{flexDirection: 'row'}}> - <View - style={{ - width: 95, - height: 10, - marginRight: 10, - marginBottom: 5, - overflow: 'hidden', - borderWidth: 0.5, - }}> - <View style={{width: 200, height: 20}}> - <Text>Overflow hidden</Text> - </View> - </View> - <View style={{width: 95, height: 10, marginBottom: 5, borderWidth: 0.5}}> - <View style={{width: 200, height: 20}}> - <Text>Overflow visible</Text> - </View> - </View> - </View> - ); - }, - }, { - title: 'Opacity', - render: function() { - return ( - <View> - <View style={{opacity: 0}}><Text>Opacity 0</Text></View> - <View style={{opacity: 0.1}}><Text>Opacity 0.1</Text></View> - <View style={{opacity: 0.3}}><Text>Opacity 0.3</Text></View> - <View style={{opacity: 0.5}}><Text>Opacity 0.5</Text></View> - <View style={{opacity: 0.7}}><Text>Opacity 0.7</Text></View> - <View style={{opacity: 0.9}}><Text>Opacity 0.9</Text></View> - <View style={{opacity: 1}}><Text>Opacity 1</Text></View> - </View> - ); - }, - }, { - title: 'ZIndex', - render: function() { - return <ZIndexExample />; - }, - }, -];
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/viewpagerandroid.html b/docs/viewpagerandroid.html index 1c7591ea567..f64d34e149b 100644 --- a/docs/viewpagerandroid.html +++ b/docs/viewpagerandroid.html @@ -1,4 +1,4 @@ -ViewPagerAndroid

    ViewPagerAndroid #

    Container that allows to flip left and right between child views. Each +ViewPagerAndroid

    ViewPagerAndroid #

    Container that allows to flip left and right between child views. Each child view of the ViewPagerAndroid will be treated as a separate page and will be stretched to fill the ViewPagerAndroid.

    It is important all children are <View>s and not composite components. You can set style properties like padding or backgroundColor for each @@ -44,264 +44,7 @@ The page scrolling state can be in 3 states: callback will have following fields: - position - index of page that has been selected

    pageMargin?: number #

    Blank space to show between pages. This is only visible while scrolling, pages are still edge-to-edge.

    scrollEnabled?: boolean #

    When false, the content does not scroll. -The default value is true.

    Type Definitions #

    ViewPagerScrollState #

    Type:
    $Enum

    Constants:
    ValueDescription
    idle
    dragging
    settling

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - Image, - StyleSheet, - Text, - TouchableWithoutFeedback, - TouchableOpacity, - View, - ViewPagerAndroid, -} = ReactNative; - -import type { ViewPagerScrollState } from 'ViewPagerAndroid'; - -var PAGES = 5; -var BGCOLOR = ['#fdc08e', '#fff6b9', '#99d1b7', '#dde5fe', '#f79273']; -var IMAGE_URIS = [ - 'https://apod.nasa.gov/apod/image/1410/20141008tleBaldridge001h990.jpg', - 'https://apod.nasa.gov/apod/image/1409/volcanicpillar_vetter_960.jpg', - 'https://apod.nasa.gov/apod/image/1409/m27_snyder_960.jpg', - 'https://apod.nasa.gov/apod/image/1409/PupAmulti_rot0.jpg', - 'https://apod.nasa.gov/apod/image/1510/lunareclipse_27Sep_beletskycrop4.jpg', -]; - -class LikeCount extends React.Component { - state = { - likes: 7, - }; - - onClick = () => { - this.setState({likes: this.state.likes + 1}); - }; - - render() { - var thumbsUp = '\uD83D\uDC4D'; - return ( - <View style={styles.likeContainer}> - <TouchableOpacity onPress={this.onClick} style={styles.likeButton}> - <Text style={styles.likesText}> - {thumbsUp + ' Like'} - </Text> - </TouchableOpacity> - <Text style={styles.likesText}> - {this.state.likes + ' likes'} - </Text> - </View> - ); - } -} - -class Button extends React.Component { - _handlePress = () => { - if (this.props.enabled && this.props.onPress) { - this.props.onPress(); - } - }; - - render() { - return ( - <TouchableWithoutFeedback onPress={this._handlePress}> - <View style={[styles.button, this.props.enabled ? {} : styles.buttonDisabled]}> - <Text style={styles.buttonText}>{this.props.text}</Text> - </View> - </TouchableWithoutFeedback> - ); - } -} - -class ProgressBar extends React.Component { - render() { - var fractionalPosition = (this.props.progress.position + this.props.progress.offset); - var progressBarSize = (fractionalPosition / (PAGES - 1)) * this.props.size; - return ( - <View style={[styles.progressBarContainer, {width: this.props.size}]}> - <View style={[styles.progressBar, {width: progressBarSize}]}/> - </View> - ); - } -} - -class ViewPagerAndroidExample extends React.Component { - static title = '<ViewPagerAndroid>'; - static description = 'Container that allows to flip left and right between child views.'; - - state = { - page: 0, - animationsAreEnabled: true, - scrollEnabled: true, - progress: { - position: 0, - offset: 0, - }, - }; - - onPageSelected = (e) => { - this.setState({page: e.nativeEvent.position}); - }; - - onPageScroll = (e) => { - this.setState({progress: e.nativeEvent}); - }; - - onPageScrollStateChanged = (state : ViewPagerScrollState) => { - this.setState({scrollState: state}); - }; - - move = (delta) => { - var page = this.state.page + delta; - this.go(page); - }; - - go = (page) => { - if (this.state.animationsAreEnabled) { - this.viewPager.setPage(page); - } else { - this.viewPager.setPageWithoutAnimation(page); - } - - this.setState({page}); - }; - - render() { - var pages = []; - for (var i = 0; i < PAGES; i++) { - var pageStyle = { - backgroundColor: BGCOLOR[i % BGCOLOR.length], - alignItems: 'center', - padding: 20, - }; - pages.push( - <View key={i} style={pageStyle} collapsable={false}> - <Image - style={styles.image} - source={{uri: IMAGE_URIS[i % BGCOLOR.length]}} - /> - <LikeCount /> - </View> - ); - } - var { page, animationsAreEnabled } = this.state; - return ( - <View style={styles.container}> - <ViewPagerAndroid - style={styles.viewPager} - initialPage={0} - scrollEnabled={this.state.scrollEnabled} - onPageScroll={this.onPageScroll} - onPageSelected={this.onPageSelected} - onPageScrollStateChanged={this.onPageScrollStateChanged} - pageMargin={10} - ref={viewPager => { this.viewPager = viewPager; }}> - {pages} - </ViewPagerAndroid> - <View style={styles.buttons}> - <Button - enabled={true} - text={this.state.scrollEnabled ? 'Scroll Enabled' : 'Scroll Disabled'} - onPress={() => this.setState({scrollEnabled: !this.state.scrollEnabled})} - /> - </View> - <View style={styles.buttons}> - { animationsAreEnabled ? - <Button - text="Turn off animations" - enabled={true} - onPress={() => this.setState({animationsAreEnabled: false})} - /> : - <Button - text="Turn animations back on" - enabled={true} - onPress={() => this.setState({animationsAreEnabled: true})} - /> } - <Text style={styles.scrollStateText}>ScrollState[ {this.state.scrollState} ]</Text> - </View> - <View style={styles.buttons}> - <Button text="Start" enabled={page > 0} onPress={() => this.go(0)}/> - <Button text="Prev" enabled={page > 0} onPress={() => this.move(-1)}/> - <Text style={styles.buttonText}>Page {page + 1} / {PAGES}</Text> - <ProgressBar size={100} progress={this.state.progress}/> - <Button text="Next" enabled={page < PAGES - 1} onPress={() => this.move(1)}/> - <Button text="Last" enabled={page < PAGES - 1} onPress={() => this.go(PAGES - 1)}/> - </View> - </View> - ); - } -} - -var styles = StyleSheet.create({ - buttons: { - flexDirection: 'row', - height: 30, - backgroundColor: 'black', - alignItems: 'center', - justifyContent: 'space-between', - }, - button: { - flex: 1, - width: 0, - margin: 5, - borderColor: 'gray', - borderWidth: 1, - backgroundColor: 'gray', - }, - buttonDisabled: { - backgroundColor: 'black', - opacity: 0.5, - }, - buttonText: { - color: 'white', - }, - scrollStateText: { - color: '#99d1b7', - }, - container: { - flex: 1, - backgroundColor: 'white', - }, - image: { - width: 300, - height: 200, - padding: 20, - }, - likeButton: { - backgroundColor: 'rgba(0, 0, 0, 0.1)', - borderColor: '#333333', - borderWidth: 1, - borderRadius: 5, - flex: 1, - margin: 8, - padding: 8, - }, - likeContainer: { - flexDirection: 'row', - }, - likesText: { - flex: 1, - fontSize: 18, - alignSelf: 'center', - }, - progressBarContainer: { - height: 10, - margin: 10, - borderColor: '#eeeeee', - borderWidth: 2, - }, - progressBar: { - alignSelf: 'flex-start', - flex: 1, - backgroundColor: '#eeeeee', - }, - viewPager: { - flex: 1, - }, -}); - -module.exports = ViewPagerAndroidExample;
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/virtualizedlist.html b/docs/virtualizedlist.html index dbf05bdac0b..a0b8df342a6 100644 --- a/docs/virtualizedlist.html +++ b/docs/virtualizedlist.html @@ -1,4 +1,4 @@ -VirtualizedList

    VirtualizedList #

    Base implementation for the more convenient <FlatList> +VirtualizedList

    VirtualizedList #

    Base implementation for the more convenient <FlatList> and <SectionList> components, which are also better documented. In general, this should only really be used if you need more flexibility than FlatList provides, e.g. for use with immutable data instead of plain arrays.

    Virtualization massively improves memory consumption and performance of large lists by @@ -7,15 +7,16 @@ window with appropriately sized blank space. The window adapts to scrolling beha are rendered incrementally with low-pri (after any running interactions) if they are far from the visible area, or with hi-pri otherwise to minimize the potential of seeing blank space.

    Some caveats:

    • Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.
    • This is a PureComponent which means that it will not re-render if props remain shallow- -equal. Make sure that everything your renderItem function depends on is passed as a prop that -is not === after updates, otherwise your UI may not update on changes. This includes the -data prop and parent component state.
    • In order to constrain memory and enable smooth scrolling, content is rendered asynchronously +equal. Make sure that everything your renderItem function depends on is passed as a prop +(e.g. extraData) that is not === after updates, otherwise your UI may not update on +changes. This includes the data prop and parent component state.
    • In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.
    • By default, the list looks for a key prop on each item and uses that for the React key. -Alternatively, you can provide a custom keyExtractor prop.

    NOTE: LayoutAnimation and sticky section headers both have bugs when used with this and are -therefore not officially supported yet.

    NOTE: removeClippedSubviews might not be necessary and may cause bugs. If you see issues with -content not rendering, try disabling it, and we may change the default there.

    Props #

    data?: any #

    The default accessor functions assume this is an Array<{key: string}> but you can override +Alternatively, you can provide a custom keyExtractor prop.

    Props #

    ListEmptyComponent?: ?ReactClass<any> | React.Element<any> #

    Rendered when the list is empty. Can be a React Component Class, a render function, or +a rendered element.

    ListFooterComponent?: ?ReactClass<any> | React.Element<any> #

    Rendered at the bottom of all the items. Can be a React Component Class, a render function, or +a rendered element.

    ListHeaderComponent?: ?ReactClass<any> | React.Element<any> #

    Rendered at the top of all the items. Can be a React Component Class, a render function, or +a rendered element.

    data?: any #

    The default accessor functions assume this is an Array<{key: string}> but you can override getItem, getItemCount, and keyExtractor to handle any type of index-based data.

    debug?: ?boolean #

    debug will turn on extra logging and visual overlays to aid with debugging both usage and implementation, but with a significant perf hit.

    disableVirtualization: boolean #

    DEPRECATED: Virtualization provides significant performance and memory optimizations, but fully unmounts react instances that are outside of the render window. You should only need to disable @@ -24,16 +25,17 @@ any of your renderItem, Header, Footer, etc. functions depend on an data prop, stick it here and treat it immutably.

    getItem: (data: any, index: number) => ?Item #

    A generic accessor for extracting an item from any sort of data blob.

    getItemCount: (data: any) => number #

    Determines how many items are in the data blob.

    getItemLayout?: (data: any, index: number) => {length: number, offset: number, index: number} #

    horizontal?: ?boolean #

    initialNumToRender: number #

    How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order -to improve perceived performance of scroll-to-top actions.

    keyExtractor: (item: Item, index: number) => string #

    maxToRenderPerBatch: number #

    The maximum number of items to render in each incremental render batch. The more rendered at +to improve perceived performance of scroll-to-top actions.

    initialScrollIndex?: ?number #

    Instead of starting at the top with the first item, start at initialScrollIndex. This +disables the "scroll to top" optimization that keeps the first initialNumToRender items +always rendered and immediately renders the items starting at this initial index. Requires +getItemLayout to be implemented.

    keyExtractor: (item: Item, index: number) => string #

    maxToRenderPerBatch: number #

    The maximum number of items to render in each incremental render batch. The more rendered at once, the better the fill rate, but responsiveness my suffer because rendering content may interfere with responding to button taps or other interactions.

    onEndReached?: ?(info: {distanceFromEnd: number}) => void #

    onEndReachedThreshold?: ?number #

    onLayout?: ?Function #

    onRefresh?: ?Function #

    If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the refreshing prop correctly.

    onViewableItemsChanged?: ?(info: { viewableItems: Array<ViewToken>, changed: Array<ViewToken>, }) => void #

    Called when the viewability of rows changes, as defined by the -viewabilityConfig prop.

    refreshing?: ?boolean #

    Set this true while waiting for new data from a refresh.

    removeClippedSubviews?: boolean #

    A native optimization that removes clipped subviews (those outside the parent) from the view -hierarchy to offload work from the native rendering system. They are still kept around so no -memory is saved and state is preserved.

    renderItem: (info: {item: Item, index: number}) => ?React.Element<any> #

    renderScrollComponent: (props: Object) => React.Element<any> #

    Render a custom scroll component, e.g. with a differently styled RefreshControl.

    updateCellsBatchingPeriod: number #

    Amount of time between low-pri item render batches, e.g. for rendering items quite a ways off +viewabilityConfig prop.

    refreshing?: ?boolean #

    Set this true while waiting for new data from a refresh.

    removeClippedSubviews?: boolean #

    Note: may have bugs (missing content) in some circumstances - use at your own risk.

    This may improve scroll performance for large lists.

    renderItem: (info: any) => ?React.Element<any> #

    renderScrollComponent: (props: Object) => React.Element<any> #

    Render a custom scroll component, e.g. with a differently styled RefreshControl.

    scrollEventThrottle?: #

    updateCellsBatchingPeriod: number #

    Amount of time between low-pri item render batches, e.g. for rendering items quite a ways off screen. Similar fill rate/responsiveness tradeoff as maxToRenderPerBatch.

    viewabilityConfig?: ViewabilityConfig #

    windowSize: number #

    Determines the maximum number of items rendered outside of the visible area, in units of visible lengths. So if your list fills the screen, then windowSize={21} (the default) will render the visible screen area plus up to 10 screens above and 10 below the viewport. Reducing @@ -54,6 +56,6 @@ chance that fast scrolling may reveal momentary blank areas of unrendered conten apiKey: '2c98749b4a1e588efec53b2acec13025', indexName: 'react-native-versions', inputSelector: '#algolia-doc-search', - algoliaOptions: { facetFilters: [ "tags:0.44" ], hitsPerPage: 5 } + algoliaOptions: { facetFilters: [ "tags:0.45" ], hitsPerPage: 5 } }); - \ No newline at end of file + \ No newline at end of file diff --git a/docs/webview.html b/docs/webview.html index 75ee8bd485a..f5c05c38ab7 100644 --- a/docs/webview.html +++ b/docs/webview.html @@ -1,4 +1,4 @@ -WebView

    WebView #

    WebView renders web content in a native view.

    import React, { Component } from 'react'; +WebView

    WebView #

    WebView renders web content in a native view.

    import React, { Component } from 'react'; import { WebView } from 'react-native'; class MyWeb extends Component { @@ -11,490 +11,79 @@ class MyWeb extends ); } }

    You can use this component to navigate back and forth in the web view's -history and configure various properties for the web content.

    Props #

    automaticallyAdjustContentInsets?: bool #

    Controls whether to adjust the content inset for web views that are +history and configure various properties for the web content.

    Props #

    automaticallyAdjustContentInsets?: PropTypes.bool #

    Controls whether to adjust the content inset for web views that are placed behind a navigation bar, tab bar, or toolbar. The default value is true.

    contentInset?: {top: number, left: number, bottom: number, right: number} #

    The amount by which the web view content is inset from the edges of -the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}.

    html?: string #

    Deprecated

    Use the source prop instead.

    injectJavaScript?: function #

    Function that accepts a string that will be passed to the WebView and -executed immediately as JavaScript.

    injectedJavaScript?: string #

    Set this to provide JavaScript that will be injected into the web page -when the view loads.

    mediaPlaybackRequiresUserAction?: bool #

    Boolean that determines whether HTML5 audio and video requires the user -to tap them before they start playing. The default value is true.

    onError?: function #

    Function that is invoked when the WebView load fails.

    onLoad?: function #

    Function that is invoked when the WebView has finished loading.

    onLoadEnd?: function #

    Function that is invoked when the WebView load succeeds or fails.

    onLoadStart?: function #

    Function that is invoked when the WebView starts loading.

    onMessage?: function #

    A function that is invoked when the webview calls window.postMessage. +the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}.

    html?: string #

    Deprecated

    Use the source prop instead.

    injectJavaScript?: PropTypes.func #

    Function that accepts a string that will be passed to the WebView and +executed immediately as JavaScript.

    injectedJavaScript?: PropTypes.string #

    Set this to provide JavaScript that will be injected into the web page +when the view loads.

    mediaPlaybackRequiresUserAction?: PropTypes.bool #

    Boolean that determines whether HTML5 audio and video requires the user +to tap them before they start playing. The default value is true.

    onError?: PropTypes.func #

    Function that is invoked when the WebView load fails.

    onLoad?: PropTypes.func #

    Function that is invoked when the WebView has finished loading.

    onLoadEnd?: PropTypes.func #

    Function that is invoked when the WebView load succeeds or fails.

    onLoadStart?: PropTypes.func #

    Function that is invoked when the WebView starts loading.

    onMessage?: PropTypes.func #

    A function that is invoked when the webview calls window.postMessage. Setting this property will inject a postMessage global into your webview, but will still call pre-existing values of postMessage.

    window.postMessage accepts one argument, data, which will be available on the event object, event.nativeEvent.data. data -must be a string.

    onNavigationStateChange?: function #

    Function that is invoked when the WebView loading starts or ends.

    renderError?: function #

    Function that returns a view to show if there's an error.

    renderLoading?: function #

    Function that returns a loading indicator.

    scalesPageToFit?: bool #

    Boolean that controls whether the web content is scaled to fit +must be a string.

    onNavigationStateChange?: PropTypes.func #

    Function that is invoked when the WebView loading starts or ends.

    renderError?: PropTypes.func #

    Function that returns a view to show if there's an error.

    renderLoading?: PropTypes.func #

    Function that returns a loading indicator.

    scalesPageToFit?: PropTypes.bool #

    Boolean that controls whether the web content is scaled to fit the view and enables the user to change the scale. The default value -is true.

    source?: {uri: string, method: string, headers: object, body: string}, {html: string, baseUrl: string}, number #

    Loads static html or a uri (with optional headers) in the WebView.

    startInLoadingState?: bool #

    Boolean value that forces the WebView to show the loading view -on the first load.

    style?: ViewPropTypes.style #

    The style to apply to the WebView.

    url?: string #

    Deprecated

    Use the source prop instead.

    androiddomStorageEnabled?: bool #

    Boolean value to control whether DOM Storage is enabled. Used only in -Android.

    androidjavaScriptEnabled?: bool #

    Boolean value to enable JavaScript in the WebView. Used on Android only -as JavaScript is enabled by default on iOS. The default value is true.

    androidmixedContentMode?: enum('never', 'always', 'compatibility') #

    Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin.

    Possible values for mixedContentMode are:

    • 'never' (default) - WebView will not allow a secure origin to load content from an insecure origin.
    • 'always' - WebView will allow a secure origin to load content from any other origin, even if that origin is insecure.
    • 'compatibility' - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content.

    androiduserAgent?: string #

    Sets the user-agent for the WebView.

    iosallowsInlineMediaPlayback?: bool #

    Boolean that determines whether HTML5 videos play inline or use the +is true.

    source?: PropTypes.oneOfType([ + PropTypes.shape({ + /* + * The URI to load in the `WebView`. Can be a local or remote file. + */ + uri: PropTypes.string, + /* + * The HTTP Method to use. Defaults to GET if not specified. + * NOTE: On Android, only GET and POST are supported. + */ + method: PropTypes.string, + /* + * Additional HTTP headers to send with the request. + * NOTE: On Android, this can only be used with GET requests. + */ + headers: PropTypes.object, + /* + * The HTTP body to send with the request. This must be a valid + * UTF-8 string, and will be sent exactly as specified, with no + * additional encoding (e.g. URL-escaping or base64) applied. + * NOTE: On Android, this can only be used with POST requests. + */ + body: PropTypes.string, + }), + PropTypes.shape({ + /* + * A static HTML page to display in the WebView. + */ + html: PropTypes.string, + /* + * The base URL to be used for any relative links in the HTML. + */ + baseUrl: PropTypes.string, + }), + /* + * Used internally by packager. + */ + PropTypes.number, +]) #

    Loads static html or a uri (with optional headers) in the WebView.

    startInLoadingState?: PropTypes.bool #

    Boolean value that forces the WebView to show the loading view +on the first load.

    style?: ViewPropTypes.style #

    The style to apply to the WebView.

    url?: string #

    Deprecated

    Use the source prop instead.

    androiddomStorageEnabled?: PropTypes.bool #

    Boolean value to control whether DOM Storage is enabled. Used only in +Android.

    androidjavaScriptEnabled?: PropTypes.bool #

    Boolean value to enable JavaScript in the WebView. Used on Android only +as JavaScript is enabled by default on iOS. The default value is true.

    androidmixedContentMode?: PropTypes.oneOf([ + 'never', + 'always', + 'compatibility' +]) #

    Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin.

    Possible values for mixedContentMode are:

    • 'never' (default) - WebView will not allow a secure origin to load content from an insecure origin.
    • 'always' - WebView will allow a secure origin to load content from any other origin, even if that origin is insecure.
    • 'compatibility' - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content.

    androiduserAgent?: PropTypes.string #

    Sets the user-agent for the WebView.

    iosallowsInlineMediaPlayback?: PropTypes.bool #

    Boolean that determines whether HTML5 videos play inline or use the native full-screen controller. The default value is false.

    NOTE : In order for video to play inline, not only does this property need to be set to true, but the video element in the HTML -document must also include the webkit-playsinline attribute.

    iosbounces?: bool #

    Boolean value that determines whether the web view bounces -when it reaches the edge of the content. The default value is true.

    iosdataDetectorTypes?: enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all'), [enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all')] #

    Determines the types of data converted to clickable URLs in the web view’s content. +document must also include the webkit-playsinline attribute.

    iosbounces?: PropTypes.bool #

    Boolean value that determines whether the web view bounces +when it reaches the edge of the content. The default value is true.

    iosdataDetectorTypes?: PropTypes.oneOfType([ + PropTypes.oneOf(DataDetectorTypes), + PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), +]) #

    Determines the types of data converted to clickable URLs in the web view’s content. By default only phone numbers are detected.

    You can provide one type or an array of many types.

    Possible values for dataDetectorTypes are:

    • 'phoneNumber'
    • 'link'
    • 'address'
    • 'calendarEvent'
    • 'none'
    • 'all'

    iosdecelerationRate?: ScrollView.propTypes.decelerationRate #

    A floating-point number that determines how quickly the scroll view decelerates after the user lifts their finger. You may also use the string shortcuts "normal" and "fast" which match the underlying iOS settings for UIScrollViewDecelerationRateNormal and -UIScrollViewDecelerationRateFast respectively:

    • normal: 0.998
    • fast: 0.99 (the default for iOS web view)

    iosonShouldStartLoadWithRequest?: function #

    Function that allows custom handling of any web view requests. Return +UIScrollViewDecelerationRateFast respectively:

    • normal: 0.998
    • fast: 0.99 (the default for iOS web view)

    iosonShouldStartLoadWithRequest?: PropTypes.func #

    Function that allows custom handling of any web view requests. Return true from the function to continue loading the request and false -to stop loading.

    iosscrollEnabled?: bool #

    Boolean value that determines whether scrolling is enabled in the -WebView. The default value is true.

    You can edit the content above on GitHub and send us a pull request!

    Examples #

    Edit on GitHub
    'use strict'; - -var React = require('react'); -var ReactNative = require('react-native'); -var { - StyleSheet, - Text, - TextInput, - TouchableWithoutFeedback, - TouchableOpacity, - View, - WebView -} = ReactNative; - -var HEADER = '#3b5998'; -var BGWASH = 'rgba(255,255,255,0.8)'; -var DISABLED_WASH = 'rgba(255,255,255,0.25)'; - -var TEXT_INPUT_REF = 'urlInput'; -var WEBVIEW_REF = 'webview'; -var DEFAULT_URL = 'https://m.facebook.com'; - -class WebViewExample extends React.Component { - state = { - url: DEFAULT_URL, - status: 'No Page Loaded', - backButtonEnabled: false, - forwardButtonEnabled: false, - loading: true, - scalesPageToFit: true, - }; - - inputText = ''; - - handleTextInputChange = (event) => { - var url = event.nativeEvent.text; - if (!/^[a-zA-Z-_]+:/.test(url)) { - url = 'http://' + url; - } - this.inputText = url; - }; - - render() { - this.inputText = this.state.url; - - return ( - <View style={[styles.container]}> - <View style={[styles.addressBarRow]}> - <TouchableOpacity - onPress={this.goBack} - style={this.state.backButtonEnabled ? styles.navButton : styles.disabledButton}> - <Text> - {'<'} - </Text> - </TouchableOpacity> - <TouchableOpacity - onPress={this.goForward} - style={this.state.forwardButtonEnabled ? styles.navButton : styles.disabledButton}> - <Text> - {'>'} - </Text> - </TouchableOpacity> - <TextInput - ref={TEXT_INPUT_REF} - autoCapitalize="none" - defaultValue={this.state.url} - onSubmitEditing={this.onSubmitEditing} - onChange={this.handleTextInputChange} - clearButtonMode="while-editing" - style={styles.addressBarTextInput} - /> - <TouchableOpacity onPress={this.pressGoButton}> - <View style={styles.goButton}> - <Text> - Go! - </Text> - </View> - </TouchableOpacity> - </View> - <WebView - ref={WEBVIEW_REF} - automaticallyAdjustContentInsets={false} - style={styles.webView} - source={{uri: this.state.url}} - javaScriptEnabled={true} - domStorageEnabled={true} - decelerationRate="normal" - onNavigationStateChange={this.onNavigationStateChange} - onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest} - startInLoadingState={true} - scalesPageToFit={this.state.scalesPageToFit} - /> - <View style={styles.statusBar}> - <Text style={styles.statusBarText}>{this.state.status}</Text> - </View> - </View> - ); - } - - goBack = () => { - this.refs[WEBVIEW_REF].goBack(); - }; - - goForward = () => { - this.refs[WEBVIEW_REF].goForward(); - }; - - reload = () => { - this.refs[WEBVIEW_REF].reload(); - }; - - onShouldStartLoadWithRequest = (event) => { - // Implement any custom loading logic here, don't forget to return! - return true; - }; - - onNavigationStateChange = (navState) => { - this.setState({ - backButtonEnabled: navState.canGoBack, - forwardButtonEnabled: navState.canGoForward, - url: navState.url, - status: navState.title, - loading: navState.loading, - scalesPageToFit: true - }); - }; - - onSubmitEditing = (event) => { - this.pressGoButton(); - }; - - pressGoButton = () => { - var url = this.inputText.toLowerCase(); - if (url === this.state.url) { - this.reload(); - } else { - this.setState({ - url: url, - }); - } - // dismiss keyboard - this.refs[TEXT_INPUT_REF].blur(); - }; -} - -class Button extends React.Component { - _handlePress = () => { - if (this.props.enabled !== false && this.props.onPress) { - this.props.onPress(); - } - }; - - render() { - return ( - <TouchableWithoutFeedback onPress={this._handlePress}> - <View style={styles.button}> - <Text>{this.props.text}</Text> - </View> - </TouchableWithoutFeedback> - ); - } -} - -class ScaledWebView extends React.Component { - state = { - scalingEnabled: true, - }; - - render() { - return ( - <View> - <WebView - style={{ - backgroundColor: BGWASH, - height: 200, - }} - source={{uri: 'https://facebook.github.io/react/'}} - scalesPageToFit={this.state.scalingEnabled} - /> - <View style={styles.buttons}> - { this.state.scalingEnabled ? - <Button - text="Scaling:ON" - enabled={true} - onPress={() => this.setState({scalingEnabled: false})} - /> : - <Button - text="Scaling:OFF" - enabled={true} - onPress={() => this.setState({scalingEnabled: true})} - /> } - </View> - </View> - ); - } -} - -class MessagingTest extends React.Component { - webview = null - - state = { - messagesReceivedFromWebView: 0, - message: '', - } - - onMessage = e => this.setState({ - messagesReceivedFromWebView: this.state.messagesReceivedFromWebView + 1, - message: e.nativeEvent.data, - }) - - postMessage = () => { - if (this.webview) { - this.webview.postMessage('"Hello" from React Native!'); - } - } - - render(): ReactElement<any> { - const {messagesReceivedFromWebView, message} = this.state; - - return ( - <View style={[styles.container, { height: 200 }]}> - <View style={styles.container}> - <Text>Messages received from web view: {messagesReceivedFromWebView}</Text> - <Text>{message || '(No message)'}</Text> - <View style={styles.buttons}> - <Button text="Send Message to Web View" enabled onPress={this.postMessage} /> - </View> - </View> - <View style={styles.container}> - <WebView - ref={webview => { this.webview = webview; }} - style={{ - backgroundColor: BGWASH, - height: 100, - }} - source={require('./messagingtest.html')} - onMessage={this.onMessage} - /> - </View> - </View> - ); - } -} - -class InjectJS extends React.Component { - webview = null; - injectJS = () => { - const script = 'document.write("Injected JS ")'; // eslint-disable-line quotes - if (this.webview) { - this.webview.injectJavaScript(script); - } - } - render() { - return ( - <View> - <WebView - ref={webview => { this.webview = webview; }} - style={{ - backgroundColor: BGWASH, - height: 300, - }} - source={{uri: 'https://www.facebook.com'}} - scalesPageToFit={true} - /> - <View style={styles.buttons}> - <Button text="Inject JS" enabled onPress={this.injectJS} /> - </View> - </View> - ); - } -} - - -var styles = StyleSheet.create({ - container: { - flex: 1, - backgroundColor: HEADER, - }, - addressBarRow: { - flexDirection: 'row', - padding: 8, - }, - webView: { - backgroundColor: BGWASH, - height: 350, - }, - addressBarTextInput: { - backgroundColor: BGWASH, - borderColor: 'transparent', - borderRadius: 3, - borderWidth: 1, - height: 24, - paddingLeft: 10, - paddingTop: 3, - paddingBottom: 3, - flex: 1, - fontSize: 14, - }, - navButton: { - width: 20, - padding: 3, - marginRight: 3, - alignItems: 'center', - justifyContent: 'center', - backgroundColor: BGWASH, - borderColor: 'transparent', - borderRadius: 3, - }, - disabledButton: { - width: 20, - padding: 3, - marginRight: 3, - alignItems: 'center', - justifyContent: 'center', - backgroundColor: DISABLED_WASH, - borderColor: 'transparent', - borderRadius: 3, - }, - goButton: { - height: 24, - padding: 3, - marginLeft: 8, - alignItems: 'center', - backgroundColor: BGWASH, - borderColor: 'transparent', - borderRadius: 3, - alignSelf: 'stretch', - }, - statusBar: { - flexDirection: 'row', - alignItems: 'center', - paddingLeft: 5, - height: 22, - }, - statusBarText: { - color: 'white', - fontSize: 13, - }, - spinner: { - width: 20, - marginRight: 6, - }, - buttons: { - flexDirection: 'row', - height: 30, - backgroundColor: 'black', - alignItems: 'center', - justifyContent: 'space-between', - }, - button: { - flex: 0.5, - width: 0, - margin: 5, - borderColor: 'gray', - borderWidth: 1, - backgroundColor: 'gray', - }, -}); - -const HTML = ` -<!DOCTYPE html>\n -<html> - <head> - <title>Hello Static World</title> - <meta http-equiv="content-type" content="text/html; charset=utf-8"> - <meta name="viewport" content="width=320, user-scalable=no"> - <style type="text/css"> - body { - margin: 0; - padding: 0; - font: 62.5% arial, sans-serif; - background: #ccc; - } - h1 { - padding: 45px; - margin: 0; - text-align: center; - color: #33f; - } - </style> - </head> - <body> - <h1>Hello Static World</h1> - </body> -</html> -`; - -exports.displayName = (undefined: ?string); -exports.title = '<WebView>'; -exports.description = 'Base component to display web content'; -exports.examples = [ - { - title: 'Simple Browser', - render(): React.Element<any> { return <WebViewExample />; } - }, - { - title: 'Scale Page to Fit', - render(): React.Element<any> { return <ScaledWebView/>; } - }, - { - title: 'Bundled HTML', - render(): React.Element<any> { - return ( - <WebView - style={{ - backgroundColor: BGWASH, - height: 100, - }} - source={require('./helloworld.html')} - scalesPageToFit={true} - /> - ); - } - }, - { - title: 'Static HTML', - render(): React.Element<any> { - return ( - <WebView - style={{ - backgroundColor: BGWASH, - height: 100, - }} - source={{html: HTML}} - scalesPageToFit={true} - /> - ); - } - }, - { - title: 'POST Test', - render(): React.Element<any> { - return ( - <WebView - style={{ - backgroundColor: BGWASH, - height: 100, - }} - source={{ - uri: 'http://www.posttestserver.com/post.php', - method: 'POST', - body: 'foo=bar&bar=foo' - }} - scalesPageToFit={false} - /> - ); - } - }, - { - title: 'Messaging Test', - render(): ReactElement<any> { return <MessagingTest />; } - }, - { - title: 'Inject JavaScript', - render(): React.Element<any> { return <InjectJS />; } - }, -];
    \ No newline at end of file + \ No newline at end of file diff --git a/img/AVDManagerMacOS.png b/img/AVDManagerMacOS.png new file mode 100644 index 00000000000..298d9f4db25 Binary files /dev/null and b/img/AVDManagerMacOS.png differ diff --git a/img/AVDManagerWindows.png b/img/AVDManagerWindows.png new file mode 100644 index 00000000000..15706357464 Binary files /dev/null and b/img/AVDManagerWindows.png differ diff --git a/img/AdministratorCommandPrompt.png b/img/AdministratorCommandPrompt.png new file mode 100644 index 00000000000..99345236bd3 Binary files /dev/null and b/img/AdministratorCommandPrompt.png differ diff --git a/img/AndroidEnvironmentVariableANDROID_HOME.png b/img/AndroidEnvironmentVariableANDROID_HOME.png new file mode 100644 index 00000000000..1e6d35caa6a Binary files /dev/null and b/img/AndroidEnvironmentVariableANDROID_HOME.png differ diff --git a/img/AndroidSDKManager.png b/img/AndroidSDKManager.png deleted file mode 100644 index eca03a0bfb6..00000000000 Binary files a/img/AndroidSDKManager.png and /dev/null differ diff --git a/img/AndroidSDKManagerInstallsMacOS.png b/img/AndroidSDKManagerInstallsMacOS.png new file mode 100644 index 00000000000..c93b57a6051 Binary files /dev/null and b/img/AndroidSDKManagerInstallsMacOS.png differ diff --git a/img/AndroidSDKManagerInstallsWindows.png b/img/AndroidSDKManagerInstallsWindows.png new file mode 100644 index 00000000000..e0e4deb7f99 Binary files /dev/null and b/img/AndroidSDKManagerInstallsWindows.png differ diff --git a/img/AndroidSDKManagerMacOS.png b/img/AndroidSDKManagerMacOS.png new file mode 100644 index 00000000000..8d0a8f3bb9f Binary files /dev/null and b/img/AndroidSDKManagerMacOS.png differ diff --git a/img/AndroidSDKManagerSDKToolsMacOS.png b/img/AndroidSDKManagerSDKToolsMacOS.png new file mode 100644 index 00000000000..44f002b5483 Binary files /dev/null and b/img/AndroidSDKManagerSDKToolsMacOS.png differ diff --git a/img/AndroidSDKManagerSDKToolsWindows.png b/img/AndroidSDKManagerSDKToolsWindows.png new file mode 100644 index 00000000000..5ea04a60483 Binary files /dev/null and b/img/AndroidSDKManagerSDKToolsWindows.png differ diff --git a/img/AndroidSDKManagerWindows.png b/img/AndroidSDKManagerWindows.png new file mode 100644 index 00000000000..fe78e2a2f45 Binary files /dev/null and b/img/AndroidSDKManagerWindows.png differ diff --git a/img/AndroidStudioCustomSetup.png b/img/AndroidStudioCustomSetup.png new file mode 100644 index 00000000000..4d7e16b6fd5 Binary files /dev/null and b/img/AndroidStudioCustomSetup.png differ diff --git a/img/AndroidStudioWelcomeMacOS.png b/img/AndroidStudioWelcomeMacOS.png new file mode 100644 index 00000000000..3ba178525ab Binary files /dev/null and b/img/AndroidStudioWelcomeMacOS.png differ diff --git a/img/AndroidStudioWelcomeWindows.png b/img/AndroidStudioWelcomeWindows.png new file mode 100644 index 00000000000..e65229bd927 Binary files /dev/null and b/img/AndroidStudioWelcomeWindows.png differ diff --git a/img/AndroidSuccess.png b/img/AndroidSuccess.png deleted file mode 100644 index bd10f089756..00000000000 Binary files a/img/AndroidSuccess.png and /dev/null differ diff --git a/img/AndroidSuccessMacOS.png b/img/AndroidSuccessMacOS.png new file mode 100644 index 00000000000..0fbb4e9f832 Binary files /dev/null and b/img/AndroidSuccessMacOS.png differ diff --git a/img/AndroidSuccessWindows.png b/img/AndroidSuccessWindows.png new file mode 100644 index 00000000000..4c653bae64f Binary files /dev/null and b/img/AndroidSuccessWindows.png differ diff --git a/img/ConfigureReleaseScheme.png b/img/ConfigureReleaseScheme.png new file mode 100644 index 00000000000..dd671cc8391 Binary files /dev/null and b/img/ConfigureReleaseScheme.png differ diff --git a/img/CreateAVD.png b/img/CreateAVD.png deleted file mode 100644 index 5a3d49445f6..00000000000 Binary files a/img/CreateAVD.png and /dev/null differ diff --git a/img/CreateAVDMacOS.png b/img/CreateAVDMacOS.png new file mode 100644 index 00000000000..ee922502962 Binary files /dev/null and b/img/CreateAVDMacOS.png differ diff --git a/img/CreateAVDWindows.png b/img/CreateAVDWindows.png new file mode 100644 index 00000000000..545663f7f17 Binary files /dev/null and b/img/CreateAVDWindows.png differ diff --git a/img/CreateAVDx86MacOS.png b/img/CreateAVDx86MacOS.png new file mode 100644 index 00000000000..c1ca88aac03 Binary files /dev/null and b/img/CreateAVDx86MacOS.png differ diff --git a/img/CreateAVDx86Windows.png b/img/CreateAVDx86Windows.png new file mode 100644 index 00000000000..681daade763 Binary files /dev/null and b/img/CreateAVDx86Windows.png differ diff --git a/img/Inspector.gif b/img/Inspector.gif new file mode 100644 index 00000000000..b7589733c82 Binary files /dev/null and b/img/Inspector.gif differ diff --git a/img/ReactDevTools.png b/img/ReactDevTools.png new file mode 100644 index 00000000000..caa3af713b3 Binary files /dev/null and b/img/ReactDevTools.png differ diff --git a/img/ReactDevToolsDollarR.gif b/img/ReactDevToolsDollarR.gif new file mode 100644 index 00000000000..373d80b90a9 Binary files /dev/null and b/img/ReactDevToolsDollarR.gif differ diff --git a/img/ReactDevToolsInspector.gif b/img/ReactDevToolsInspector.gif new file mode 100644 index 00000000000..c3540bee79c Binary files /dev/null and b/img/ReactDevToolsInspector.gif differ diff --git a/img/RunningOnDeviceCodeSigning.png b/img/RunningOnDeviceCodeSigning.png new file mode 100644 index 00000000000..8bf01d61e7f Binary files /dev/null and b/img/RunningOnDeviceCodeSigning.png differ diff --git a/img/RunningOnDeviceReady.png b/img/RunningOnDeviceReady.png new file mode 100644 index 00000000000..e251d1663bd Binary files /dev/null and b/img/RunningOnDeviceReady.png differ diff --git a/img/react-native-android-sdk-environment-variable-windows.png b/img/react-native-android-sdk-environment-variable-windows.png deleted file mode 100644 index 6b3d9810a53..00000000000 Binary files a/img/react-native-android-sdk-environment-variable-windows.png and /dev/null differ diff --git a/img/react-native-tools-avd.png b/img/react-native-tools-avd.png index 66683ddd259..20d7626ecbf 100644 Binary files a/img/react-native-tools-avd.png and b/img/react-native-tools-avd.png differ diff --git a/index.html b/index.html index 3ab75d14624..7550019bf45 100644 --- a/index.html +++ b/index.html @@ -1,4 +1,4 @@ -React Native | A framework for building native apps using React
    React Native
    Learn once, write anywhere: Build mobile apps with React

    Build native mobile apps using JavaScript and React

    React Native lets you build mobile apps using only JavaScript. It uses the same design as React, letting you compose a rich mobile UI from declarative components.

    import React, { Component } from 'react'; +React Native | A framework for building native apps using React
    React Native
    Learn once, write anywhere: Build mobile apps with React

    Build native mobile apps using JavaScript and React

    React Native lets you build mobile apps using only JavaScript. It uses the same design as React, letting you compose a rich mobile UI from declarative components.

    import React, { Component } from 'react'; import { Text, View } from 'react-native'; class WhyReactNativeIsSoGreat extends Component { @@ -52,7 +52,7 @@ class SomethingFast extends /View> ); } -}

    Who's using React Native?

    Thousands of apps are using React Native, from established Fortune 500 companies to hot new startups. If you're curious to see what can be accomplished with React Native, check out these apps!

    Facebook
    Facebook Ads Manager
    Instagram
    Airbnb
    Walmart
    Tesla
    Tencent QQ
    Baidu Mobile (手机百度)
    Bloomberg
    Vogue
    li.st
    Discord
    Gyroscope
    Townske

    Some of these are hybrid native/React Native apps.

    \ No newline at end of file + \ No newline at end of file diff --git a/js/scripts.js b/js/scripts.js index ed2bb3eb695..a6294fbbc0f 100644 --- a/js/scripts.js +++ b/js/scripts.js @@ -23,7 +23,9 @@ var mobile = isMobile(); if (mobile) { - document.querySelector('.nav-site-wrapper a[data-target]').addEventListener('click', toggleTarget); + document + .querySelector('.nav-site-wrapper a[data-target]') + .addEventListener('click', toggleTarget); } var webPlayerList = document.querySelectorAll('.web-player'); @@ -33,13 +35,36 @@ webPlayerList[i].classList.add(mobile ? 'mobile' : 'desktop'); if (!mobile) { - // Determine location to look up required assets - var assetRoot = encodeURIComponent(document.location.origin + '/react-native'); + var assetRoot = encodeURIComponent( + document.location.origin + '/react-native' + ); // Set iframe src. Do this dynamically so the iframe never loads on mobile. var iframe = webPlayerList[i].querySelector('iframe'); - iframe.src = iframe.getAttribute('data-src') + '&assetRoot=' + assetRoot; + iframe.src = iframe.getAttribute('data-src') + + '&assetRoot=' + + assetRoot; + } + } + + var snackPlayerList = document.querySelectorAll('.snack-player'); + + // Either show interactive or static code block, depending on desktop or mobile + for (var i = 0; i < snackPlayerList.length; ++i) { + var snackPlayer = snackPlayerList[i]; + var snackDesktopPlayer = snackPlayer.querySelectorAll( + '.desktop-friendly-snack' + )[0]; + var plainCodeExample = snackPlayer.querySelectorAll( + '.mobile-friendly-snack' + )[0]; + + if (mobile) { + snackDesktopPlayer.remove(); + plainCodeExample.style.display = 'block'; + } else { + plainCodeExample.remove(); } } @@ -86,7 +111,9 @@ var toggledTarget; function toggleTarget(event) { - var target = document.body.querySelector(event.target.getAttribute('data-target')); + var target = document.body.querySelector( + event.target.getAttribute('data-target') + ); if (target) { event.preventDefault(); @@ -104,7 +131,8 @@ // Primitive mobile detection function isMobile() { - return ( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ); + return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( + navigator.userAgent + ); } - -}()); +})(); diff --git a/releases/0.45/versions.html b/releases/0.45/versions.html index 17841d71b69..d59834e3304 100644 --- a/releases/0.45/versions.html +++ b/releases/0.45/versions.html @@ -1,4 +1,4 @@ -React Native Versions

    React Native Versions

    React Native follows a monthly release train. Every month, a new branch created off master enters the Release Candidate phase, and the previous Release Candidate branch is released and considered stable.

    If you have an existing project that uses React Native, read the release notes to learn about new features and fixes. You can follow our guide to upgrade your app to the latest version.

    Current version (Stable)

    0.44DocumentationRelease Notes

    This is the version that is configured automatically when you create a new project using react-native init.

    Pre-release versions

    masterDocumentation
    0.45-RCDocumentationRelease Notes

    To see what changes are coming and provide better feedback to React Native contributors, use the latest release candidate when possible. By the time a release candidate is released, the changes it contains will have been shipped in production Facebook apps for over two weeks.

    Past versions

    0.43DocumentationRelease Notes
    0.42DocumentationRelease Notes
    0.41DocumentationRelease Notes
    0.40DocumentationRelease Notes
    0.39DocumentationRelease Notes
    0.38DocumentationRelease Notes
    0.37DocumentationRelease Notes
    0.36DocumentationRelease Notes
    0.35DocumentationRelease Notes
    0.34DocumentationRelease Notes
    0.33DocumentationRelease Notes
    0.32DocumentationRelease Notes
    0.31DocumentationRelease Notes
    0.30DocumentationRelease Notes
    0.29DocumentationRelease Notes
    0.28DocumentationRelease Notes
    0.27DocumentationRelease Notes
    0.26DocumentationRelease Notes
    0.25DocumentationRelease Notes
    0.24DocumentationRelease Notes
    0.23DocumentationRelease Notes
    0.22DocumentationRelease Notes
    0.21DocumentationRelease Notes
    0.20DocumentationRelease Notes
    0.19DocumentationRelease Notes
    0.18DocumentationRelease Notes

    You can find past versions of React Native on GitHub. The release notes can be useful if you would like to learn when a specific feature or fix was released.

    You can also view the docs for a particular version of React Native by clicking on the Docs link next to the release in this page. You can come back to this page and switch the version of the docs you're reading at any time by clicking on the version number at the top of the page.

    React Native Versions

    React Native follows a monthly release train. Every month, a new branch created off master enters the Release Candidate phase, and the previous Release Candidate branch is released and considered stable.

    If you have an existing project that uses React Native, read the release notes to learn about new features and fixes. You can follow our guide to upgrade your app to the latest version.

    Current version (Stable)

    0.45DocumentationRelease Notes

    This is the version that is configured automatically when you create a new project using react-native init.

    Pre-release versions

    masterDocumentation

    To see what changes are coming and provide better feedback to React Native contributors, use the latest release candidate when possible. By the time a release candidate is released, the changes it contains will have been shipped in production Facebook apps for over two weeks.

    Past versions

    0.44DocumentationRelease Notes
    0.43DocumentationRelease Notes
    0.42DocumentationRelease Notes
    0.41DocumentationRelease Notes
    0.40DocumentationRelease Notes
    0.39DocumentationRelease Notes
    0.38DocumentationRelease Notes
    0.37DocumentationRelease Notes
    0.36DocumentationRelease Notes
    0.35DocumentationRelease Notes
    0.34DocumentationRelease Notes
    0.33DocumentationRelease Notes
    0.32DocumentationRelease Notes
    0.31DocumentationRelease Notes
    0.30DocumentationRelease Notes
    0.29DocumentationRelease Notes
    0.28DocumentationRelease Notes
    0.27DocumentationRelease Notes
    0.26DocumentationRelease Notes
    0.25DocumentationRelease Notes
    0.24DocumentationRelease Notes
    0.23DocumentationRelease Notes
    0.22DocumentationRelease Notes
    0.21DocumentationRelease Notes
    0.20DocumentationRelease Notes
    0.19DocumentationRelease Notes
    0.18DocumentationRelease Notes

    You can find past versions of React Native on GitHub. The release notes can be useful if you would like to learn when a specific feature or fix was released.

    You can also view the docs for a particular version of React Native by clicking on the Docs link next to the release in this page. You can come back to this page and switch the version of the docs you're reading at any time by clicking on the version number at the top of the page.

    React Native Versions

    React Native follows a monthly release train. Every month, a new branch created off master enters the Release Candidate phase, and the previous Release Candidate branch is released and considered stable.

    If you have an existing project that uses React Native, read the release notes to learn about new features and fixes. You can follow our guide to upgrade your app to the latest version.

    Current version (Stable)

    0.44DocumentationRelease Notes

    This is the version that is configured automatically when you create a new project using react-native init.

    Pre-release versions

    masterDocumentation
    0.45-RCDocumentationRelease Notes

    To see what changes are coming and provide better feedback to React Native contributors, use the latest release candidate when possible. By the time a release candidate is released, the changes it contains will have been shipped in production Facebook apps for over two weeks.

    Past versions

    0.43DocumentationRelease Notes
    0.42DocumentationRelease Notes
    0.41DocumentationRelease Notes
    0.40DocumentationRelease Notes
    0.39DocumentationRelease Notes
    0.38DocumentationRelease Notes
    0.37DocumentationRelease Notes
    0.36DocumentationRelease Notes
    0.35DocumentationRelease Notes
    0.34DocumentationRelease Notes
    0.33DocumentationRelease Notes
    0.32DocumentationRelease Notes
    0.31DocumentationRelease Notes
    0.30DocumentationRelease Notes
    0.29DocumentationRelease Notes
    0.28DocumentationRelease Notes
    0.27DocumentationRelease Notes
    0.26DocumentationRelease Notes
    0.25DocumentationRelease Notes
    0.24DocumentationRelease Notes
    0.23DocumentationRelease Notes
    0.22DocumentationRelease Notes
    0.21DocumentationRelease Notes
    0.20DocumentationRelease Notes
    0.19DocumentationRelease Notes
    0.18DocumentationRelease Notes

    You can find past versions of React Native on GitHub. The release notes can be useful if you would like to learn when a specific feature or fix was released.

    You can also view the docs for a particular version of React Native by clicking on the Docs link next to the release in this page. You can come back to this page and switch the version of the docs you're reading at any time by clicking on the version number at the top of the page.

    React Native Versions

    React Native follows a monthly release train. Every month, a new branch created off master enters the Release Candidate phase, and the previous Release Candidate branch is released and considered stable.

    If you have an existing project that uses React Native, read the release notes to learn about new features and fixes. You can follow our guide to upgrade your app to the latest version.

    Current version (Stable)

    0.45DocumentationRelease Notes

    This is the version that is configured automatically when you create a new project using react-native init.

    Pre-release versions

    masterDocumentation

    To see what changes are coming and provide better feedback to React Native contributors, use the latest release candidate when possible. By the time a release candidate is released, the changes it contains will have been shipped in production Facebook apps for over two weeks.

    Past versions

    0.44DocumentationRelease Notes
    0.43DocumentationRelease Notes
    0.42DocumentationRelease Notes
    0.41DocumentationRelease Notes
    0.40DocumentationRelease Notes
    0.39DocumentationRelease Notes
    0.38DocumentationRelease Notes
    0.37DocumentationRelease Notes
    0.36DocumentationRelease Notes
    0.35DocumentationRelease Notes
    0.34DocumentationRelease Notes
    0.33DocumentationRelease Notes
    0.32DocumentationRelease Notes
    0.31DocumentationRelease Notes
    0.30DocumentationRelease Notes
    0.29DocumentationRelease Notes
    0.28DocumentationRelease Notes
    0.27DocumentationRelease Notes
    0.26DocumentationRelease Notes
    0.25DocumentationRelease Notes
    0.24DocumentationRelease Notes
    0.23DocumentationRelease Notes
    0.22DocumentationRelease Notes
    0.21DocumentationRelease Notes
    0.20DocumentationRelease Notes
    0.19DocumentationRelease Notes
    0.18DocumentationRelease Notes

    You can find past versions of React Native on GitHub. The release notes can be useful if you would like to learn when a specific feature or fix was released.

    You can also view the docs for a particular version of React Native by clicking on the Docs link next to the release in this page. You can come back to this page and switch the version of the docs you're reading at any time by clicking on the version number at the top of the page.

    \ No newline at end of file