diff --git a/releases/0.47/404.html b/releases/0.47/404.html new file mode 100644 index 00000000000..db93f09777f --- /dev/null +++ b/releases/0.47/404.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/releases/0.47/circle.yml b/releases/0.47/circle.yml new file mode 100644 index 00000000000..56ad41b2f14 --- /dev/null +++ b/releases/0.47/circle.yml @@ -0,0 +1,4 @@ +general: + branches: + ignore: + - gh-pages diff --git a/releases/0.47/css/prism.css b/releases/0.47/css/prism.css new file mode 100644 index 00000000000..e1b64e2eea8 --- /dev/null +++ b/releases/0.47/css/prism.css @@ -0,0 +1,138 @@ +/* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript+bash+c+git+java+json+objectivec+powershell+jsx+swift */ +/** + * prism.js default theme for JavaScript, CSS and HTML + * Based on dabblet (http://dabblet.com) + * @author Lea Verou + */ + +code[class*="language-"], +pre[class*="language-"] { + color: black; + background: none; + text-shadow: 0 1px white; + font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; + text-align: left; + white-space: pre; + word-spacing: normal; + word-break: normal; + word-wrap: normal; + line-height: 1.5; + + -moz-tab-size: 4; + -o-tab-size: 4; + tab-size: 4; + + -webkit-hyphens: none; + -moz-hyphens: none; + -ms-hyphens: none; + hyphens: none; +} + +pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, +code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { + text-shadow: none; + background: #b3d4fc; +} + +pre[class*="language-"]::selection, pre[class*="language-"] ::selection, +code[class*="language-"]::selection, code[class*="language-"] ::selection { + text-shadow: none; + background: #b3d4fc; +} + +@media print { + code[class*="language-"], + pre[class*="language-"] { + text-shadow: none; + } +} + +/* Code blocks */ +pre[class*="language-"] { + padding: 1em; + margin: .5em 0; + overflow: auto; +} + +:not(pre) > code[class*="language-"], +pre[class*="language-"] { + background: #f5f2f0; +} + +/* Inline code */ +:not(pre) > code[class*="language-"] { + padding: .1em; + border-radius: .3em; + white-space: normal; +} + +.token.comment, +.token.prolog, +.token.doctype, +.token.cdata { + color: slategray; +} + +.token.punctuation { + color: #999; +} + +.namespace { + opacity: .7; +} + +.token.property, +.token.tag, +.token.boolean, +.token.number, +.token.constant, +.token.symbol, +.token.deleted { + color: #905; +} + +.token.selector, +.token.attr-name, +.token.string, +.token.char, +.token.builtin, +.token.inserted { + color: #690; +} + +.token.operator, +.token.entity, +.token.url, +.language-css .token.string, +.style .token.string { + color: #a67f59; + background: hsla(0, 0%, 100%, .5); +} + +.token.atrule, +.token.attr-value, +.token.keyword { + color: #07a; +} + +.token.function { + color: #DD4A68; +} + +.token.regex, +.token.important, +.token.variable { + color: #e90; +} + +.token.important, +.token.bold { + font-weight: bold; +} +.token.italic { + font-style: italic; +} + +.token.entity { + cursor: help; +} diff --git a/releases/0.47/css/react-native.css b/releases/0.47/css/react-native.css new file mode 100644 index 00000000000..f82b4d34d47 --- /dev/null +++ b/releases/0.47/css/react-native.css @@ -0,0 +1,2123 @@ +/*! normalize.css v5.0.0 | MIT License | github.com/necolas/normalize.css */ +/* Document + ========================================================================== */ +/** + * 1. Change the default font family in all browsers (opinionated). + * 2. Correct the line height in all browsers. + * 3. Prevent adjustments of font size after orientation changes in + * IE on Windows Phone and in iOS. + */ +html { + font-family: sans-serif; + /* 1 */ + line-height: 1.15; + /* 2 */ + -ms-text-size-adjust: 100%; + /* 3 */ + -webkit-text-size-adjust: 100%; + /* 3 */ } + +/* Sections + ========================================================================== */ +/** + * Remove the margin in all browsers (opinionated). + */ +body { + margin: 0; } + +/** + * Add the correct display in IE 9-. + */ +article, +aside, +footer, +header, +nav, +section { + display: block; } + +/** + * Correct the font size and margin on `h1` elements within `section` and + * `article` contexts in Chrome, Firefox, and Safari. + */ +h1 { + font-size: 2em; + margin: 0.67em 0; } + +/* Grouping content + ========================================================================== */ +/** + * Add the correct display in IE 9-. + * 1. Add the correct display in IE. + */ +figcaption, +figure, +main { + /* 1 */ + display: block; } + +/** + * Add the correct margin in IE 8. + */ +figure { + margin: 1em 40px; } + +/** + * 1. Add the correct box sizing in Firefox. + * 2. Show the overflow in Edge and IE. + */ +hr { + box-sizing: content-box; + /* 1 */ + height: 0; + /* 1 */ + overflow: visible; + /* 2 */ } + +/** + * 1. Correct the inheritance and scaling of font size in all browsers. + * 2. Correct the odd `em` font sizing in all browsers. + */ +pre { + font-family: monospace, monospace; + /* 1 */ + font-size: 1em; + /* 2 */ } + +/* Text-level semantics + ========================================================================== */ +/** + * 1. Remove the gray background on active links in IE 10. + * 2. Remove gaps in links underline in iOS 8+ and Safari 8+. + */ +a { + background-color: transparent; + /* 1 */ + -webkit-text-decoration-skip: objects; + /* 2 */ } + +/** + * Remove the outline on focused links when they are also active or hovered + * in all browsers (opinionated). + */ +a:active, +a:hover { + outline-width: 0; } + +/** + * 1. Remove the bottom border in Firefox 39-. + * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari. + */ +abbr[title] { + border-bottom: none; + /* 1 */ + text-decoration: underline; + /* 2 */ + text-decoration: underline dotted; + /* 2 */ } + +/** + * Prevent the duplicate application of `bolder` by the next rule in Safari 6. + */ +b, +strong { + font-weight: inherit; } + +/** + * Add the correct font weight in Chrome, Edge, and Safari. + */ +b, +strong { + font-weight: bolder; } + +/** + * 1. Correct the inheritance and scaling of font size in all browsers. + * 2. Correct the odd `em` font sizing in all browsers. + */ +code, +kbd, +samp { + font-family: monospace, monospace; + /* 1 */ + font-size: 1em; + /* 2 */ } + +/** + * Add the correct font style in Android 4.3-. + */ +dfn { + font-style: italic; } + +/** + * Add the correct background and color in IE 9-. + */ +mark { + background-color: #ff0; + color: #000; } + +/** + * Add the correct font size in all browsers. + */ +small { + font-size: 80%; } + +/** + * Prevent `sub` and `sup` elements from affecting the line height in + * all browsers. + */ +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; } + +sub { + bottom: -0.25em; } + +sup { + top: -0.5em; } + +/* Embedded content + ========================================================================== */ +/** + * Add the correct display in IE 9-. + */ +audio, +video { + display: inline-block; } + +/** + * Add the correct display in iOS 4-7. + */ +audio:not([controls]) { + display: none; + height: 0; } + +/** + * Remove the border on images inside links in IE 10-. + */ +img { + border-style: none; } + +/** + * Hide the overflow in IE. + */ +svg:not(:root) { + overflow: hidden; } + +/* Forms + ========================================================================== */ +/** + * 1. Change the font styles in all browsers (opinionated). + * 2. Remove the margin in Firefox and Safari. + */ +button, +input, +optgroup, +select, +textarea { + font-family: sans-serif; + /* 1 */ + font-size: 100%; + /* 1 */ + line-height: 1.15; + /* 1 */ + margin: 0; + /* 2 */ } + +/** + * Show the overflow in IE. + * 1. Show the overflow in Edge. + */ +button, +input { + /* 1 */ + overflow: visible; } + +/** + * Remove the inheritance of text transform in Edge, Firefox, and IE. + * 1. Remove the inheritance of text transform in Firefox. + */ +button, +select { + /* 1 */ + text-transform: none; } + +/** + * 1. Prevent a WebKit bug where (2) destroys native `audio` and `video` + * controls in Android 4. + * 2. Correct the inability to style clickable types in iOS and Safari. + */ +button, +html [type="button"], +[type="reset"], +[type="submit"] { + -webkit-appearance: button; + /* 2 */ } + +/** + * Remove the inner border and padding in Firefox. + */ +button::-moz-focus-inner, +[type="button"]::-moz-focus-inner, +[type="reset"]::-moz-focus-inner, +[type="submit"]::-moz-focus-inner { + border-style: none; + padding: 0; } + +/** + * Restore the focus styles unset by the previous rule. + */ +button:-moz-focusring, +[type="button"]:-moz-focusring, +[type="reset"]:-moz-focusring, +[type="submit"]:-moz-focusring { + outline: 1px dotted ButtonText; } + +/** + * Change the border, margin, and padding in all browsers (opinionated). + */ +fieldset { + border: 1px solid #c0c0c0; + margin: 0 2px; + padding: 0.35em 0.625em 0.75em; } + +/** + * 1. Correct the text wrapping in Edge and IE. + * 2. Correct the color inheritance from `fieldset` elements in IE. + * 3. Remove the padding so developers are not caught out when they zero out + * `fieldset` elements in all browsers. + */ +legend { + box-sizing: border-box; + /* 1 */ + color: inherit; + /* 2 */ + display: table; + /* 1 */ + max-width: 100%; + /* 1 */ + padding: 0; + /* 3 */ + white-space: normal; + /* 1 */ } + +/** + * 1. Add the correct display in IE 9-. + * 2. Add the correct vertical alignment in Chrome, Firefox, and Opera. + */ +progress { + display: inline-block; + /* 1 */ + vertical-align: baseline; + /* 2 */ } + +/** + * Remove the default vertical scrollbar in IE. + */ +textarea { + overflow: auto; } + +/** + * 1. Add the correct box sizing in IE 10-. + * 2. Remove the padding in IE 10-. + */ +[type="checkbox"], +[type="radio"] { + box-sizing: border-box; + /* 1 */ + padding: 0; + /* 2 */ } + +/** + * Correct the cursor style of increment and decrement buttons in Chrome. + */ +[type="number"]::-webkit-inner-spin-button, +[type="number"]::-webkit-outer-spin-button { + height: auto; } + +/** + * 1. Correct the odd appearance in Chrome and Safari. + * 2. Correct the outline style in Safari. + */ +[type="search"] { + -webkit-appearance: textfield; + /* 1 */ + outline-offset: -2px; + /* 2 */ } + +/** + * Remove the inner padding and cancel buttons in Chrome and Safari on macOS. + */ +[type="search"]::-webkit-search-cancel-button, +[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; } + +/** + * 1. Correct the inability to style clickable types in iOS and Safari. + * 2. Change font properties to `inherit` in Safari. + */ +::-webkit-file-upload-button { + -webkit-appearance: button; + /* 1 */ + font: inherit; + /* 2 */ } + +/* Interactive + ========================================================================== */ +/* + * Add the correct display in IE 9-. + * 1. Add the correct display in Edge, IE, and Firefox. + */ +details, +menu { + display: block; } + +/* + * Add the correct display in all browsers. + */ +summary { + display: list-item; } + +/* Scripting + ========================================================================== */ +/** + * Add the correct display in IE 9-. + */ +canvas { + display: inline-block; } + +/** + * Add the correct display in IE. + */ +template { + display: none; } + +/* Hidden + ========================================================================== */ +/** + * Add the correct display in IE 10-. + */ +[hidden] { + display: none; } + +html { + font-family: proxima-nova, "Helvetica Neue", Helvetica, Arial, sans-serif; + color: #484848; + line-height: 1.28; } + +body { + background-color: #F5FCFF; } + +* { + -moz-box-sizing: border-box; + -ms-box-sizing: border-box; + -o-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; + border: none; + margin: 0; + padding: 0; } + +p { + margin: 0 0 16px; + line-height: 1.4; } + +em { + font-style: italic; } + +h1, h2, h3, h4, h5, h6 { + margin: 10px 0; + font-family: inherit; + font-weight: 400; + line-height: 20px; + color: #025268; + text-rendering: optimizelegibility; } + +h1 small, h2 small, h3 small, h4 small, h5 small, h6 small { + font-weight: normal; + color: #7b7b7b; } + +h1, h2, h3, h4 { + line-height: 40px; } + +h1 { + font-size: 40px; } + +h2 { + font-size: 31px; } + +h3 { + font-size: 23px; } + +h4 { + font-size: 17px; } + +h5 { + font-size: 14px; } + +h6 { + font-size: 11px; } + +h1 small { + font-size: 24px; } + +h2 small { + font-size: 18px; } + +h3 small { + font-size: 16px; } + +h4 small { + font-size: 14px; } + +img { + max-width: 100%; + height: auto; } + +ul, ol { + margin: 0 0 10px 25px; + padding: 0; } + +ul ul, ul ol, ol ol, ol ul { + margin-bottom: 0; } + +li { + line-height: 20px; } + +a { + color: #05A5D1; + text-decoration: none; } + +a:hover, a:focus { + color: #047e9f; + text-decoration: underline; } + +a:focus { + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; } + +.center { + text-align: center; } + +html * { + color-profile: sRGB; + rendering-intent: auto; } + +.content { + font-size: 18px; +} +.subHeader { + font-size: 21px; + font-weight: 300; + line-height: 30px; + margin-bottom: 10px; } + +.example-container { + position: relative; } + +.embedded-simulator, .embedded-simulator * { + box-sizing: border-box; } + +.embedded-simulator p { + text-align: center; + color: #999; } + +.embedded-simulator { + width: 210px; + position: absolute; + right: -200px; + top: 0; } + +@media screen and (max-width: 680px) { + .embedded-simulator { + position: relative; + right: 0; } } + +.side-by-side { + overflow: hidden; } + +.side-by-side > div { + width: 460; + margin-left: 0; + float: left; } + +.left { + float: left; } + +.right { + float: right; } + +.container { + padding-top: 50px; + min-width: 1160px; } + +.wrap { + max-width: 1260px; + margin: 0 auto; + padding: 0 20px; } + +.skinnyWrap { + width: 690px; + margin-left: auto; + margin-right: auto; + padding-left: 20px; + padding-right: 20px; } + +hr { + height: 0; + border-top: 1px solid #ccc; + border-bottom: 1px solid #eee; } + +ul, li { + margin-left: 20px; } + +h1 .anchor, h2 .anchor, h3 .anchor, h4 .anchor, h5 .anchor, h6 .anchor { + margin-top: -50px; + position: absolute; } + +h1:hover .hash-link, h2:hover .hash-link, h3:hover .hash-link, h4:hover .hash-link, h5:hover .hash-link, h6:hover .hash-link { + visibility: visible; } + +.hash-link { + color: #aaa; + visibility: hidden; } + +.nav-main { + *zoom: 1; + background: #222; + color: #fafafa; + position: fixed; + top: 0; + min-height: 50px; + width: 100%; + z-index: 100; + box-shadow: 0 0 5px rgba(0, 0, 0, 0.5); } + +.nav-main:before, .nav-main:after { + content: " "; + display: table; } + +.nav-main:after { + clear: both; } + +.nav-main a { + color: #e9e9e9; + text-decoration: none; } + +.nav-main .nav-site-wrapper { + display: inline; + float: right; +} + +.nav-main .nav-site-internal { + margin: 0 0 0 20px; } + +.nav-main .nav-site-external { + float: right; + margin: 0 12px 0 0; } + +.nav-main .nav-site li { + margin: 0; } + +.nav-main .nav-site a { + box-sizing: content-box; + padding: 0 10px; + line-height: 50px; + display: inline-block; + height: 50px; } + +.nav-site-wrapper a:hover { + color: #fff; } + +.nav-site-wrapper a.active { + color: #fff; + border-bottom: 3px solid #05A5D1; + background-color: #2D2D2D; } + +.nav-main .nav-home { + font-size: 24px; + font-weight: 300; + line-height: 50px; } + +.nav-home img { + vertical-align: -9px; + margin-right: 8px; + margin-left: 1px; + width: 34px; } + +.nav-main a.nav-home { + color: white; } + +.nav-main ul { + display: inline-block; + vertical-align: top; } + +.nav-main li { + display: inline; } + +.nav-main a.nav-version { + font-size: 16px; + font-weight: 300; + margin-left: 8px; + text-decoration: underline; } + +@media screen and (max-width: 680px) { + .nav-main .nav-home { + font-size: 20px; } + .nav-main a.nav-version { + font-size: 14px; } + .nav-main .nav-site-wrapper { + display: block; + overflow: hidden; } + .nav-main ul { + display: -webkit-flex; + display: flex; + overflow: hidden; } + .nav-main li { + -webkit-flex: 1; + flex: 1; } + .nav-main .nav-site li a { + width: 100%; + padding: 0; + text-align: center; + font-size: 14px; } + .nav-main .nav-site a.active { + color: #05A5D1; + font-weight: 300; + background-color: transparent; } + .nav-main .nav-site-internal { + margin: 0; + width: 100%; } + .nav-main .nav-site-external { + position: absolute; + top: 0; + right: 0; + float: none; } + .nav-main .nav-site-external li a { + padding: 0 6px; } } + +.nav-docs { + font-size: 14px; + float: left; + width: 210px; + margin: 0 48px 0 0; } + .nav-docs ul { + list-style: none; + margin: 0; + margin-left: 1px; } + .nav-docs ul ul { + margin-left: 20px; } + .nav-docs li { + margin: 0; } + .nav-docs a:hover { + text-decoration: none; + color: #025268; } + .nav-docs a.active { + color: #05A5D1; + font-weight: bold; } + +.nav-docs-section { + background-color: rgba(59, 55, 56, 0.05); + padding-bottom: 0; } + .nav-docs-section h3 { + color: white; + font-size: 18px; + font-weight: 400; + line-height: 20px; + margin-top: 0; + margin-bottom: 5px; + padding: 10px; + background-color: #222; + text-transform: capitalize; } + .nav-docs-section ul { + display: block; + padding-bottom: 10px; + padding-top: 10px; } + .nav-docs-section a { + color: #025268; + display: block; + margin: 2px 10px 5px; } + .nav-docs-section .nav-docs-section:first-child h3 { + margin-top: 0; } + .nav-docs-section .nav-docs-section:first-child { + padding-top: 0; + border-top: 0; } + .nav-docs-section .nav-docs-section:last-child { + padding-bottom: 0; + border-bottom: 0; } + +@media only screen and (max-device-width: 1024px) { + @-webkit-keyframes slide-in { + 0% { + top: -30px; + opacity: 0; } + 100% { + top: 0; + opacity: 1; } } + @-moz-keyframes slide-in { + 0% { + top: -30px; + opacity: 0; } + 100% { + top: 0; + opacity: 1; } } + @-o-keyframes slide-in { + 0% { + top: -30px; + opacity: 0; } + 100% { + top: 0; + opacity: 1; } } + @keyframes slide-in { + 0% { + top: -30px; + opacity: 0; } + 100% { + top: 0; + opacity: 1; } } + .nav-docs { + position: fixed; + z-index: 90; + top: -100%; + left: 0; + width: 100%; + height: 100%; + margin: 0; + padding: 53px 0 0 0; + background: #3B3738; } + .nav-docs-viewport { + border-top: 1px solid #05a5d1; + padding: 25px; + overflow: scroll; + -webkit-overflow-scrolling: touch; + position: relative; + width: 100%; + height: 100%; } + /* Active state */ + .nav-docs.in { + top: 0; + -moz-animation: slide-in 0.3s forwards; + -ms-animation: slide-in 0.3s forwards; + -o-animation: slide-in 0.3s forwards; + -webkit-animation: slide-in 0.3s forwards; + animation: slide-in 0.3s forwards; } + .nav-docs * { + -webkit-font-smoothing: antialiased; } + .nav-docs-section + .nav-docs-section { + margin-top: 50px; } + .nav-docs-section li { + margin: 5px 0; } + .nav-docs-section h3, + .nav-docs-section a { + color: white; } + .nav-docs-section h3 { + border-bottom: 1px solid white; + margin-bottom: 10px; + opacity: 0.3; } + .nav-docs-section a { + margin-right: 25px; + font-size: 120%; + padding: 5px 0; } + .nav-docs-section a.active { + border-bottom-style: solid; + border-bottom-width: 1px; + color: #05A5D1; } } + +/** + * Multicolumn layout for phone (landscape only) & tablet (regardless its screen orientation)/ + */ +@media only screen and (min-device-width: 375px) and (max-device-width: 1024px) { + .nav-docs-section ul { + display: flex; + flex-wrap: wrap; } + .nav-docs-section li { + width: 100%; } } + +/* 2 columns layout */ +@media only screen and (min-device-width: 375px) and (max-device-width: 1024px) and (orientation: landscape), only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) { + .nav-docs-section li { + width: 50%; } } + +/* 3 columns layout on tablet (landscape screen orientation) */ +@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) { + .nav-docs-section li { + width: 33%; } } + +.home-section { + margin: 50px 0; } + +.home-section ol { + margin-left: 0; } + +.home-divider { + border-top-color: #bbb; + margin: 0 auto; + width: 400px; } + +.marketing-row { + *zoom: 1; + margin: 50px 0; } + +.marketing-row:before, .marketing-row:after { + content: " "; + display: table; } + +.marketing-row:after { + clear: both; } + +.marketing-col { + float: left; + margin-left: 40px; + width: 280px; } + +.marketing-col h3 { + color: #2d2d2d; + font-size: 24px; + font-weight: normal; + text-transform: uppercase; } + +.marketing-col p { + font-size: 16px; } + +.marketing-col:first-child { + margin-left: 0; } + +.tutorial-mock { + text-align: center; } + +.tutorial-mock img { + border: 1px solid #ccc; + box-shadow: 5px 5px 5px #888888; } + +#examples h3, .home-presentation h3 { + color: #2d2d2d; + font-size: 24px; + font-weight: normal; + margin-bottom: 5px; } + +#examples p { + margin: 0 0 25px 0; + max-width: 600px; } + +#examples .example { + margin-top: 60px; } + +#examples #todoExample { + font-size: 14px; } + +#examples #todoExample ul { + list-style-type: square; + margin: 0 0 10px 0; } + +#examples #todoExample input { + border: 1px solid #ccc; + font-size: 14px; + padding: 3px; + width: 150px; } + +#examples #todoExample button { + font-size: 14px; + margin-left: 5px; + padding: 4px 10px; } + +#examples #markdownExample textarea { + border: 1px solid #ccc; + font-size: 14px; + margin-bottom: 10px; + padding: 5px; } + +.home-get-started-section { + margin-bottom: 60px; } + +.docs-nextprev { + *zoom: 1; +} + +.docs-nextprev:before, .docs-nextprev:after { + content: " "; + display: table; } + +.docs-nextprev:after { + clear: both; } + +.docs-prev { + float: left; } + +.docs-next { + float: right; } + +section.black content { + padding-bottom: 18px; } + +.blogContent { + *zoom: 1; + padding-top: 20px; } + +.blogContent:before, .blogContent:after { + content: " "; + display: table; } + +.blogContent:after { + clear: both; } + +.blogContent blockquote { + padding: 5px 15px; + margin: 20px 0; + background-color: #f8f5ec; + border-left: 5px solid #f7ebc6; } + +.documentationContent { + *zoom: 1; + padding-top: 20px; + padding-bottom: 80px; } + +.documentationContent:before, .documentationContent:after { + content: " "; + display: table; } + +.documentationContent:after { + clear: both; } + +.documentationContent .subHeader { + font-size: 24px; } + +h2 { + margin-top: 30px; } + +.documentationContent blockquote { + padding: 15px 30px 15px 15px; + margin: 20px 0; + background-color: rgba(248, 245, 236, 0.1); + border-left: 5px solid rgba(191, 87, 73, 0.2); } + +.documentationContent blockquote h4 { + margin-top: 0; } + +.documentationContent blockquote p { + margin-bottom: 0; } + +.documentationContent blockquote p:first-child { + font-size: 14px; + line-height: 20px; + margin-top: 0; + text-rendering: optimizelegibility; } + +.docs-prevnext { + min-width: 320px; + max-width: 640px; + margin: 40px auto; + padding-bottom: 20px; } + +.button { + background: -webkit-linear-gradient(#9a9a9a, #646464); + background: linear-gradient(#9a9a9a, #646464); + border-radius: 4px; + padding: 8px 16px; + font-size: 18px; + font-weight: 300; + margin: 0 12px; + display: inline-block; + color: #fafafa; + text-decoration: none; + text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3); + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2); } + +.button:hover { + text-decoration: none; } + +.button:active { + box-shadow: none; } + +.hero .button { + box-shadow: 1px 3px 3px rgba(0, 0, 0, 0.3); } + +.button.blue { + background: -webkit-linear-gradient(#77a3d2, #4783c2); + background: linear-gradient(#77a3d2, #4783c2); } + +.row { + padding-bottom: 4px; } + +.row .span4 { + width: 33.33%; + display: table-cell; } + +.row .span8 { + width: 66.66%; + display: table-cell; } + +.row .span6 { + width: 50%; + display: table-cell; } + +p { + margin: 16px 0; } + +.highlight { + padding: 10px; + margin-bottom: 20px; } + +figure { + text-align: center; } + +.inner-content { + float: left; + width: 650px; } + +.showcaseSection .inner-content { + width: 800px; } + +.helpSection .inner-content { + width: 800px; } + +.nosidebar .inner-content { + float: none; + margin: 0 auto; } + +.post-list-item + .post-list-item { + margin-top: 60px; } + +small code, li code, p code { + color: #555; + background-color: rgba(0, 0, 0, 0.04); + padding: 1px 3px; } + +.playground { + *zoom: 1; } + +.playground:before, .playground:after { + content: " "; + display: table; } + +.playground:after { + clear: both; } + +.playground-tab { + border-bottom: none !important; + border-radius: 3px 3px 0 0; + padding: 6px 8px; + font-size: 12px; + font-weight: bold; + color: #c2c0bc; + background-color: #f1ede4; + display: inline-block; + cursor: pointer; } + +.playgroundCode, .playground-tab, .playgroundPreview { + border: 1px solid rgba(16, 16, 16, 0.1); } + +.playground-tab-active { + color: #222; } + +.playgroundCode { + border-radius: 0 3px 3px 3px; + float: left; + overflow: hidden; + width: 600px; } + +.playgroundPreview { + background-color: white; + border-radius: 3px; + float: right; + padding: 15px 20px; + width: 280px; } + +.playgroundError { + color: #c5695c; + font-size: 15px; } + +.MarkdownEditor textarea { + width: 100%; + height: 100px; } + +.hll { + background-color: #f7ebc6; + border-left: 5px solid #f7d87c; + display: block; + margin-left: -14px; + margin-right: -14px; + padding-left: 9px; } + +.highlight .javascript .err { + background-color: transparent; + color: inherit; } + +.highlight { + position: relative; + margin-bottom: 14px; + padding: 30px 14px 14px; + border: none; + border-radius: 0; + overflow: auto; } + +.highlight pre { + padding: 0; + margin-top: 0; + margin-bottom: 0; + background-color: transparent; + border: 0; } + +.highlight pre code { + background: none; + font-size: inherit; + padding: 0; } + +.highlight pre .lineno { + display: inline-block; + width: 22px; + padding-right: 5px; + margin-right: 10px; + color: #bebec5; + text-align: right; } + +.highlight:after { + position: absolute; + top: 0; + right: 0; + left: 0; + padding: 3px 7px; + font-size: 12px; + font-weight: bold; + color: #c2c0bc; + background-color: #f1ede4; + content: "Code"; } + +.downloadCenter { + text-align: center; + margin-top: 20px; + margin-bottom: 25px; } + +.downloadSection:hover { + text-decoration: none !important; } + +/* Modal */ +.modal-backdrop { + background: rgba(0, 0, 0, 0.4); + display: none; + height: 100%; + left: 0; + overflow: auto; + position: fixed; + top: 0; + width: 100%; + z-index: 9900; } + +.modal { + background: #F6F6F6; + bottom: 0; + box-shadow: 2px 2px 4px 0 rgba(0, 0, 0, 0.11); + display: none; + border-radius: 10px; + height: 95%; + left: 0; + margin: auto; + max-height: 648px; + max-width: 460px; + overflow: auto; + position: fixed; + right: 0; + top: 0; + width: 80%; + z-index: 9999; } + +.modal-open { + display: block; } + +.modal-content { + padding: 40px 24px 8px 24px; + position: relative; } + +.modal-content iframe { + margin: 0 auto; } + +.modal-button-open { + cursor: pointer; + text-align: center; } + +.modal-button-open-img { + height: 358px; } + +.modal-button-open-img:hover img { + opacity: 0.9; } + +.modal-button-close { + background: transparent; + border-radius: 0 0 0 4px; + border: 0; + color: #555; + font-size: 1.2em; + font-weight: bolder; + line-height: 32px; + margin: 0; + padding: 0 12px; + position: absolute; + right: 0; + top: 0; } + +.modal-button-close:active, +.modal-button-close:focus, +.modal-button-close:hover { + background: #EAF8FD; + outline: none; } + +@media screen and (max-width: 680px) { + .container { + padding-top: 100px; } + .nav-docs { + padding-top: 103px; } } + +.post { + margin-bottom: 30px; } + +.pagination { + margin-bottom: 30px; + width: 100%; + overflow: hidden; } + +.pagination .next { + float: right; } + +div[data-twttr-id] iframe { + margin: 10px auto !important; } + +.three-column { + *zoom: 1; } + +.three-column:before, .three-column:after { + content: " "; + display: table; } + +.three-column:after { + clear: both; } + +.three-column > ul { + float: left; + margin-left: 30px; + width: 190px; } + +.three-column > ul:first-child { + margin-left: 20px; } + +.home-why { + margin-top: 25px; } + +.home-why h3 { + text-align: center; } + +.home-why .blurb { + margin-bottom: 20px; + text-align: center; } + +.home-why .list { + margin: 0 auto; + max-width: 460px; } + +.home-getting-started { + width: 500px; + margin: 20px auto 40px auto; } + +.home-getting-started h3 { + text-align: center; } + +.props { + background-color: #ebf9ff; } + +.compactProps { + border-left: 2px solid #e0f6ff; + margin-left: 20px; + padding-left: 5px; } + +.props > .prop:nth-child(2n) { + background-color: #e0f6ff; } + +.propTitle { + font-weight: bold; + font-size: 16px; } + +.compactProps .propTitle { + font-size: 14px; + margin-bottom: 0; + margin-top: 0; } + +.compactProps .propTitle div { + font-weight: normal; + margin-left: 20px; } + +.methodTitle { + font-weight: bold; + font-size: 24px; + color: #025268; } + +.compactProps .methodTitle { + font-size: 14px; + margin-bottom: 0; + margin-top: 0; } + +.compactProps .methodTitle div { + font-weight: normal; + margin-left: 20px; } + +.prop { + word-wrap: break-word; + padding: 5px 10px; } + +.compactProps .prop { + padding: 3px 10px; } + +.propType { + font-family: 'source-code-pro', Menlo, 'Courier New', Consolas, monospace; + font-weight: normal; + font-size: 15px; + white-space: pre-wrap; } + +.compactProps .propType { + font-weight: normal; + font-size: 13px; } + +.methodType { + font-weight: normal; + font-size: 24px; } + +.compactProps .methodType { + font-weight: normal; + font-size: 13px; } + +.platform { + background-color: #bdebff; + border-radius: 5px; + margin-right: 5px; + padding: 0 5px; + font-size: 13px; + font-weight: normal; + -moz-user-select: none; + -ms-user-select: none; + -o-user-select: none; + -webkit-user-select: none; + user-select: none; } + +.color { + display: inline-block; + width: 20px; + height: 20px; + margin-right: 5px; + position: relative; + top: 5px; } + +.color::before { + content: ''; + display: block; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + border: 1px solid rgba(0, 0, 0, 0.2); } + +.deprecated { + margin-bottom: 24px; } + +.deprecatedTitle { + margin-bottom: 6px; + line-height: 18px; + font-weight: bold; + color: #ffa500; } + +.deprecatedIcon { + width: 18px; + height: 18px; + margin-right: 8px; + vertical-align: top; } + +.deprecatedMessage { + margin-left: 26px; } + +#content { + display: none; } + +table.versions { + width: 60%; } + +.versions th { + width: 20%; } + +.versions td, .versions th { + padding: 2px 5px; } + +.versions tr:nth-child(2n+1) { + background-color: #e0f6ff; } + +@media only screen and (max-device-width: 1024px) { + #content { + display: inline; } + .container { + min-width: 0; + overflow: auto; } + .wrap { + width: auto; } + .home-getting-started { + width: auto; } + .inner-content { + width: auto; + float: none; } + .marketing-col { + margin-left: 0; + float: none; + margin-bottom: 30px; + text-align: center; } + .home-section, .marketing-row { + margin: 0; } + .nav-main .nav-site a { + padding: 0 8px; } + .nav-main .nav-home { + margin-left: 8px; } + .nav-main .wrap { + padding: 0; } + .home-divider { + display: none; } + .hero { + padding: 10px 0 30px 0; } + .prism { + padding: 4px 8px; + margin-left: -12px; + font-size: 11px; } + .nav-docs .nav-docs-section { + border: none; + padding: 0; } + h1 { + font-size: 30px; + line-height: 30px; } + ol { + margin: 0; } } + +@media only screen and (max-device-width: 840px) { + .showcaseSection .inner-content { + width: 100%; } + .helpSection .inner-content { + width: 100%; } } + +.params, .props { + border-spacing: 0; + border: 0; + border-collapse: collapse; } + +.params .name, .props .name, .name code { + color: #4D4E53; } + +.params td, .params th, .props td, .props th { + border: 1px solid #ddd; + margin: 0px; + text-align: left; + vertical-align: top; + padding: 4px 6px; + display: table-cell; } + +.params thead tr, .props thead tr { + background-color: #c9eaf7; + font-weight: bold; } + +.params .params thead tr, .props .props thead tr { + background-color: #fff; + font-weight: bold; } + +.params th, .props th { + border-right: 1px solid #aaa; } + +.params thead .last, .props thead .last { + border-right: 1px solid #ddd; } + +.params td.description > div > p:first-child, +.props td.description > div > p:first-child { + margin-top: 0; + padding-top: 0; } + +.params td.description > p:last-child, +.props td.description > p:last-child { + margin-bottom: 0; + padding-bottom: 0; } + +.edit-page-block { + padding: 5px; + margin: 40px auto; + font-size: 12px; + color: #887766; + text-align: center; + background-color: rgba(5, 165, 209, 0.05); } + +.banner-crna-ejected { + border: 1px solid #05A5D1; + border-radius: 3px; + margin-bottom: 40px; } + .banner-crna-ejected h3 { + font-size: 16px; + margin: 0; + padding: 0 10px; + background-color: #05A5D1; + color: white; } + .banner-crna-ejected p { + padding: 10px; + margin: 2px; + text-decoration: none !important; + background-color: white; } + +.prism { + white-space: pre-wrap; + font-family: 'source-code-pro', Menlo, 'Courier New', Consolas, monospace; + font-size: 13px; + line-height: 20px; + border-left: 4px solid #05A5D1; + padding: 5px 10px; + background-color: rgba(5, 165, 209, 0.05); + overflow: auto; } + +.prism + .prism { + margin-top: 10px; } + +.token.keyword { + color: #1990B8; } + +.token.string, .token.regex { + color: #2F9C0A; } + +.token.boolean, .token.number { + color: #C92C2C; } + +.token.comment { + color: #7D8B99; } + +/** Algolia Doc Search **/ +div.algolia-search-wrapper { + display: inline-block; + vertical-align: top; + margin-left: 15px; } + +@media screen and (max-width: 960px) { + div.algolia-search-wrapper { + display: none; } } + +input#algolia-doc-search { + background: transparent url("../img/search.png") no-repeat 10px center; + background-size: 16px 16px; + font-family: inherit; + padding: 0 10px; + padding-left: 35px; + margin-top: 10px; + height: 30px; + font-size: 16px; + line-height: 20px; + background-color: #2f2f2f; + border-radius: 4px; + color: inherit; + outline: none; + border: none; + width: 170px; + -moz-transition: 0.5s width ease; + -ms-transition: 0.5s width ease; + -o-transition: 0.5s width ease; + -webkit-transition: 0.5s width ease; + transition: 0.5s width ease; } + +input#algolia-doc-search::placeholder { + color: rgba(255, 255, 255, 0.8); } + +input#algolia-doc-search::-moz-placeholder { + color: rgba(255, 255, 255, 0.8); } + +input#algolia-doc-search:-ms-input-placeholder { + color: rgba(255, 255, 255, 0.8); } + +input#algolia-doc-search::-webkit-input-placeholder { + color: rgba(255, 255, 255, 0.8); } + +input#algolia-doc-search:focus { + width: 220px; } + +.algolia-autocomplete { + vertical-align: top; + height: 53px; } + .algolia-autocomplete .aa-dropdown-menu { + margin-left: -210px; + margin-top: -4px; } + +.algolia-docsearch-suggestion--category-header .algolia-docsearch-suggestion--highlight { + background-color: #05A5D1; } + +.aa-cursor .algolia-docsearch-suggestion--content { + color: #05A5D1; } + +.aa-cursor .algolia-docsearch-suggestion { + background: #ebf9ff; } + +.algolia-docsearch-suggestion { + border-bottom-color: #e0f6ff; } + .algolia-docsearch-suggestion--category-header { + background-color: #3B3738; } + .algolia-docsearch-suggestion--highlight { + color: #05A5D1; } + .algolia-docsearch-suggestion--subcategory-column { + border-right-color: #e0f6ff; + background-color: #ebf9ff; + color: #3B3738; } + +.hero { + background: #2D2D2D; + padding: 50px 0; + color: #FDF3E7; + font-weight: 300; } + +.hero .text { + font-size: 300%; + text-align: center; } + +.hero .minitext { + 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; } + +.buttons-unit a { + color: #FA6900; } + +.buttons-unit .button { + background: #05A5D1; + color: #fafafa; } + +@media screen and (min-width: 600px) { + .buttons-unit .button { + font-size: 24px; } +} + +.buttons-unit .button:active { + background: #0485A9; } + +.buttons-unit.downloads { + margin: 30px 0; } + +.component-grid { + max-width: 800px; +} + +.component { + border: 1px solid #05A5D1; + border-radius: 3px; + margin: 0 auto 10px; + width: 100%; + display: inline-block; + background-color: white; +} + +.component h3 { + font-size: 16px; + margin: 0; + padding: 0 10px; + background-color: #05A5D1; + color: white; +} + +.component h3 a { + color: white; +} + +.component p { + padding: 10px; + margin: 2px; +} + +@media only screen and (min-device-width: 768px) { + .component-grid { + width: 768px; + } + .component-grid.component-grid-border { + border-bottom: 1px solid #f1eff0; + } + .component { + width: 30%; + height: 150px; + margin: 0 22px 22px auto; + vertical-align: top; + } +} + +/** Showcase **/ +.home-showcase-section { + max-width: 800px; + margin: 20px auto 100px auto; + text-align: center; } + +.home-showcase-section p { + max-width: 540px; + margin: 0 auto; } + +.footnote { + font-size: 12px; + color: rgba(0, 0, 0, 0.4); } + +.home-showcase-section .showcase img { + width: 100px; + height: 100px; + border-radius: 20px; } + +.showcaseHeader { + padding-bottom: 15px; + padding-top: 15px; + text-align: center; } + +.showcase { + margin: 30px auto 30px auto; + width: 50%; + display: inline-block; + text-align: center; + vertical-align: top; } + +@media only screen and (min-device-width: 1024px) { + .showcase { + width: 25%; } } + +.showcase h3 { + margin-bottom: 0px; + line-height: 20px; + padding-left: 5px; + padding-right: 5px; + font-size: 16px; } + +.showcase p { + margin-top: 5px; } + +.showcase h3, .showcase p { + color: #484848; } + +.showcase img { + width: 100px; + height: 100px; + border-radius: 20px; } + +.pinned img { + width: 150px; + border-radius: 20px; } + +/** Web player **/ +.web-player > iframe, .web-player > .prism { + display: none; } + +.web-player.desktop > iframe { + display: block; } + +.web-player.mobile > .prism { + display: block; } + +/** Help **/ +.helpSection h2 { + font-size: 24px; } + +.help-row { + margin: 50px 0; } + +.help-row:after { + content: ""; + display: table; + clear: both; } + +.help-col { + float: left; } + +.help-col p { + font-size: 16px; } + +.help-col h3 { + color: #2d2d2d; + font-size: 18px; + line-height: 28px; + font-weight: normal; } + +@media (min-width: 600px) { + .help-col { + float: left; + margin-left: 40px; + width: 240px; } + .help-col:first-child { + margin-left: 0; } } + +.help-list { + padding: 0; + list-style: none; + margin: 1.25em 0 1em 0; } + +.entry ul, li { + margin: 0; } + +.help-list .help-list-entry { + padding: 16px 0; + border-top: 1px solid #f1eff0; } + +/** Blog **/ +.entry-header { + margin: 0; } + +.entry-header h1 { + margin: 0; + font-size: 33px; + line-height: 36px; + line-height: 1; } + +.entry-header h4 { + margin: 0 0 10px; + line-height: 16px; + font-size: 14px; + line-height: 1; } + +.entry-header .author { + color: #5A6b77; + font-weight: 700; } + +.entry-header .date { + color: rgba(102, 99, 122, 0.5); } + +.entry-readmore { + margin: 12px 0 0; } + +.entry-share { + padding: 36px 0; + display: block; + text-align: left; } + +@media screen and (max-width: 768px) { + .entry-share { + display: none; } } + +.entry-excerpt { + min-width: 320px; + max-width: 640px; + margin: 0 auto 40px; + padding-bottom: 40px; + border-bottom: 1px solid #EDEDED; } + +.entry-body { + min-width: 320px; + max-width: 640px; + margin: 0 auto; } + +.small-title { + font-size: 10px; + color: #66637A; + letter-spacing: .4rem; + text-transform: uppercase; + font-weight: 400; + line-height: 12px; } + +.entry-share .small-title { + float: left; + width: 50%; } + +.social-buttons { + padding-top: 7px; + float: left; + width: 50%; } + +article { + margin: 0 0 40px 0; } + +article h2 { + font-size: 26px; + line-height: 1; } + +article li { + line-height: 28px; } + +.author-info { + margin-top: 26px; + text-align: center; + border-bottom: 1px solid #f1f1f1; + padding-bottom: 20px; } + +.the-image { + position: relative; + display: block; + width: 64px; + height: 64px; + margin: 0 auto; + border-radius: 50%; + background-position: center center; + background-color: #fff; + background-size: cover; } + +.author-image { + position: relative; } + +.author-image:before { + content: ""; + display: block; + position: absolute; + width: 100%; + height: 1px; + top: 50%; + left: 0; + background-color: #F1F1F1; } + +.posted-on { + font-size: 12px; + color: #9d9b9b; + margin-bottom: 0; + margin-top: 15px; } + +.name-title { + margin-top: 2px; + font-size: 22px; + font-weight: 400; + margin: 3px 0 5px; + color: #5A6B77; } + +.name-title a { + color: #5A6B77; } + +.name-title .title { + color: #9d9b9b; } + +.btn { + background: 0 0; + color: #05A5D1; + min-width: 0; + border: 1px solid #05A5D1; + display: inline-block; + padding: 9px 18px; + border-radius: 4px; + text-align: center; +} + +.btn a { + text-decoration: none !important; } + +.btn:hover { + text-decoration: none !important; } + +.video-container { + border-radius: 4px; + background-clip: padding-box; + margin: 0 0 18px; + height: 180px; + width: 100%; + background-size: cover; + background-position: center center; + position: relative; + height: 0; + overflow: hidden; } + +@media (min-width: 760px) { + .video-container { + height: 345px; } } + +#mc_embed_signup { + clear: left; + width: 100%; } + +/** Footer **/ +footer.nav-footer { + box-sizing: border-box; + border: none; + font-weight: normal; + color: #202020; + font-size: 15px; + line-height: 24px; + background: #012129; + box-shadow: inset 0 10px 10px -5px rgba(0, 0, 0, 0.2); + padding-top: 2em; + padding-bottom: 2em; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; } + +footer .sitemap { + display: flex; + justify-content: space-between; + max-width: 1080px; + margin: 0 auto 1em; } + +footer .sitemap div { + flex: 1; } + +footer .sitemap .nav-home { + display: table; + margin: -12px 20px 0 0; + padding: 10px; + width: 50px; + height: 50px; + opacity: 0.4; + transition: opacity 0.15s ease-in-out; } + +footer .sitemap .nav-home:hover, +footer .sitemap .nav-home:focus { + opacity: 1.0; } + +@media screen and (max-width: 768px) { + footer .sitemap { + display: none; } + footer .newsletter { + display: none; } + #mc_embed_signup { + display: none; } } + +footer .sitemap a { + color: white; + display: table; + margin: 2px -10px; + padding: 3px 10px; } + +footer .sitemap a:hover, +footer .sitemap a:focus { + color: #05A5D1; + text-decoration: none; } + +footer .sitemap h5 > a:hover, +footer .sitemap h5 > a:focus { + color: white; + text-decoration: none; } + +footer .sitemap h5, +footer .sitemap h6 { + margin: 0 0 10px; } + +footer .sitemap h5, +footer .sitemap h6, +footer .sitemap h5 > a, +footer .sitemap h6 > a { + color: #05A5D1; + font-size: 15px; +} + +footer .sitemap h5 > a, +footer .sitemap h6 > a { + margin: 0 -10px; } + +footer .fbOpenSource { + display: block; + margin: 1em auto; + opacity: 0.4; + transition: opacity 0.15s ease-in-out; + width: 170px; } + +footer .fbOpenSource:hover { + opacity: 1.0; } + +footer .copyright { + color: rgba(255, 255, 255, 0.4); + text-align: center; } + +footer .newsletter { + display: flex; + justify-content: space-between; + max-width: 640px; + margin: 0 auto 1em; } + +footer .newsletter h5 { + color: #05A5D1; + margin: 0 0 10px; } diff --git a/releases/0.47/docs/accessibility.html b/releases/0.47/docs/accessibility.html new file mode 100644 index 00000000000..23b5b4e9a21 --- /dev/null +++ b/releases/0.47/docs/accessibility.html @@ -0,0 +1,60 @@ +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}> + <View style={styles.button}> + <Text style={styles.buttonText}>Press me!</Text> + </View> +</TouchableOpacity>

In the above example, the accessibilityLabel on the TouchableOpacity element would default to "Press me!". The label is constructed by concatenating all Text node children separated by spaces.

accessibilityTraits (iOS) #

Accessibility traits tell a person using VoiceOver what kind of element they have selected. Is this element a label? A button? A header? These questions are answered by accessibilityTraits.

To use, set the accessibilityTraits property to one of (or an array of) accessibility trait strings:

  • none Used when the element has no traits.
  • button Used when the element should be treated as a button.
  • link Used when the element should be treated as a link.
  • header Used when an element acts as a header for a content section (e.g. the title of a navigation bar).
  • search Used when the text field element should also be treated as a search field.
  • image Used when the element should be treated as an image. Can be combined with button or link, for example.
  • selected Used when the element is selected. For example, a selected row in a table or a selected button within a segmented control.
  • plays Used when the element plays its own sound when activated.
  • key Used when the element acts as a keyboard key.
  • text Used when the element should be treated as static text that cannot change.
  • summary Used when an element can be used to provide a quick summary of current conditions in the app when the app first launches. For example, when Weather first launches, the element with today's weather conditions is marked with this trait.
  • disabled Used when the control is not enabled and does not respond to user input.
  • frequentUpdates Used when the element frequently updates its label or value, but too often to send notifications. Allows an accessibility client to poll for changes. A stopwatch would be an example.
  • startsMedia Used when activating an element starts a media session (e.g. playing a movie, recording audio) that should not be interrupted by output from an assistive technology, like VoiceOver.
  • adjustable Used when an element can be "adjusted" (e.g. a slider).
  • allowsDirectInteraction Used when an element allows direct touch interaction for VoiceOver users (for example, a view representing a piano keyboard).
  • pageTurn Informs VoiceOver that it should scroll to the next page when it finishes reading the contents of the element.

accessibilityViewIsModal (iOS) #

A Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver.

For example, in a window that contains sibling views A and B, setting accessibilityViewIsModal to true on view B causes VoiceOver to ignore the elements in the view A. +On the other hand, if view B contains a child view C and you set accessibilityViewIsModal to true on view C, VoiceOver does not ignore the elements in view A.

onAccessibilityTap (iOS) #

Use this property to assign a custom function to be called when someone activates an accessible element by double tapping on it while it's selected.

onMagicTap (iOS) #

Assign this property to a custom function which will be called when someone performs the "magic tap" gesture, which is a double-tap with two fingers. A magic tap function should perform the most relevant action a user could take on a component. In the Phone app on iPhone, a magic tap answers a phone call, or ends the current one. If the selected element does not have an onMagicTap function, the system will traverse up the view hierarchy until it finds a view that does.

accessibilityComponentType (Android) #

In some cases, we also want to alert the end user of the type of selected component (i.e., that it is a “button”). If we were using native buttons, this would work automatically. Since we are using javascript, we need to provide a bit more context for TalkBack. To do so, you must specify the ‘accessibilityComponentType’ property for any UI component. For instances, we support ‘button’, ‘radiobutton_checked’ and ‘radiobutton_unchecked’ and so on.

<TouchableWithoutFeedback accessibilityComponentType=”button” + onPress={this._onPress}> + <View style={styles.button}> + <Text style={styles.buttonText}>Press me!</Text> + </View> +</TouchableWithoutFeedback>

In the above example, the TouchableWithoutFeedback is being announced by TalkBack as a native Button.

accessibilityLiveRegion (Android) #

When components dynamically change, we want TalkBack to alert the end user. This is made possible by the ‘accessibilityLiveRegion’ property. It can be set to ‘none’, ‘polite’ and ‘assertive’:

  • none Accessibility services should not announce changes to this view.
  • polite Accessibility services should announce changes to this view.
  • assertive Accessibility services should interrupt ongoing speech to immediately announce changes to this view.
<TouchableWithoutFeedback onPress={this._addOne}> + <View style={styles.embedded}> + <Text>Click me</Text> + </View> +</TouchableWithoutFeedback> +<Text accessibilityLiveRegion="polite"> + Clicked {this.state.count} times +</Text>

In the above example method _addOne changes the state.count variable. As soon as an end user clicks the TouchableWithoutFeedback, TalkBack reads text in the Text view because of its 'accessibilityLiveRegion=”polite”' property.

importantForAccessibility (Android) #

In the case of two overlapping UI components with the same parent, default accessibility focus can have unpredictable behavior. The ‘importantForAccessibility’ property will resolve this by controlling if a view fires accessibility events and if it is reported to accessibility services. It can be set to ‘auto’, ‘yes’, ‘no’ and ‘no-hide-descendants’ (the last value will force accessibility services to ignore the component and all of its children).

<View style={styles.container}> + <View style={{position: 'absolute', left: 10, top: 10, right: 10, height: 100, + backgroundColor: 'green'}} importantForAccessibility=”yes”> + <Text> First layout </Text> + </View> + <View style={{position: 'absolute', left: 10, top: 10, right: 10, height: 100, + backgroundColor: 'yellow'}} importantForAccessibility=”no-hide-descendants”> + <Text> Second layout </Text> + </View> +</View>

In the above example, the yellow layout and its descendants are completely invisible to TalkBack and all other accessibility services. So we can easily use overlapping views with the same parent without confusing TalkBack.

Checking if a Screen Reader is Enabled #

The AccessibilityInfo API allows you to determine whether or not a screen reader is currently active. See the AccessibilityInfo documentation for details.

Sending Accessibility Events (Android) #

Sometimes it is useful to trigger an accessibility event on a UI component (i.e. when a custom view appears on a screen or a custom radio button has been selected). Native UIManager module exposes a method ‘sendAccessibilityEvent’ for this purpose. It takes two arguments: view tag and a type of an event.

_onPress: function() { + this.state.radioButton = this.state.radioButton === “radiobutton_checked” ? + “radiobutton_unchecked” : “radiobutton_checked”; + if (this.state.radioButton === “radiobutton_checked”) { + RCTUIManager.sendAccessibilityEvent( + ReactNative.findNodeHandle(this), + RCTUIManager.AccessibilityEventTypes.typeViewClicked); + } +} + +<CustomRadioButton + accessibleComponentType={this.state.radioButton} + onPress={this._onPress}/>

In the above example we've created a custom radio button that now behaves like a native one. More specifically, TalkBack now correctly announces changes to the radio button selection.

Testing VoiceOver Support (iOS) #

To enable VoiceOver, go to the Settings app on your iOS device. Tap General, then Accessibility. There you will find many tools that people use to make their devices more usable, such as bolder text, increased contrast, and VoiceOver.

To enable VoiceOver, tap on VoiceOver under "Vision" and toggle the switch that appears at the top.

At the very bottom of the Accessibility settings, there is an "Accessibility Shortcut". You can use this to toggle VoiceOver by triple clicking the Home button.

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

\ No newline at end of file diff --git a/releases/0.47/docs/accessibilityinfo.html b/releases/0.47/docs/accessibilityinfo.html new file mode 100644 index 00000000000..19bc8b066dc --- /dev/null +++ b/releases/0.47/docs/accessibilityinfo.html @@ -0,0 +1,66 @@ +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 = { + screenReaderEnabled: false, + } + + componentDidMount() { + AccessibilityInfo.addEventListener( + 'change', + this._handleScreenReaderToggled + ); + AccessibilityInfo.fetch().done((isEnabled) => { + this.setState({ + screenReaderEnabled: isEnabled + }); + }); + } + + componentWillUnmount() { + AccessibilityInfo.removeEventListener( + 'change', + this._handleScreenReaderToggled + ); + } + + _handleScreenReaderToggled = (isEnabled) => { + this.setState({ + screenReaderEnabled: isEnabled, + }); + } + + render() { + return ( + <View> + <Text> + The screen reader is {this.state.screenReaderEnabled ? 'enabled' : 'disabled'}. + </Text> + </View> + ); + } +}

Methods #

static fetch() #

Query whether a screen reader is currently enabled. Returns a promise which +resolves to a boolean. The result is true when a screen reader is enabled +and false otherwise.

static addEventListener(eventName, handler) #

Add an event handler. Supported events:

  • change: Fires when the state of the screen reader changes. The argument +to the event handler is a boolean. The boolean is true when a screen +reader is enabled and false otherwise.
  • announcementFinished: iOS-only event. Fires when the screen reader has +finished making an announcement. The argument to the event handler is a dictionary +with these keys:
    • announcement: The string announced by the screen reader.
    • success: A boolean indicating whether the announcement was successfully made.

static setAccessibilityFocus(reactTag) #

iOS-Only. Set accessibility focus to a react component.

static announceForAccessibility(announcement) #

iOS-Only. Post a string to be announced by the screen reader.

static removeEventListener(eventName, handler) #

Remove an event handler.

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

\ No newline at end of file diff --git a/releases/0.47/docs/actionsheetios.html b/releases/0.47/docs/actionsheetios.html new file mode 100644 index 00000000000..83e0e59df7f --- /dev/null +++ b/releases/0.47/docs/actionsheetios.html @@ -0,0 +1,24 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/activityindicator.html b/releases/0.47/docs/activityindicator.html new file mode 100644 index 00000000000..caa6c6104a5 --- /dev/null +++ b/releases/0.47/docs/activityindicator.html @@ -0,0 +1,23 @@ +ActivityIndicator

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 diff --git a/releases/0.47/docs/adsupportios.html b/releases/0.47/docs/adsupportios.html new file mode 100644 index 00000000000..652b0b95ab8 --- /dev/null +++ b/releases/0.47/docs/adsupportios.html @@ -0,0 +1,24 @@ +AdSupportIOS

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 diff --git a/releases/0.47/docs/alert.html b/releases/0.47/docs/alert.html new file mode 100644 index 00000000000..4ef0db83090 --- /dev/null +++ b/releases/0.47/docs/alert.html @@ -0,0 +1,39 @@ +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, +see AlertIOS; entering text in an alert is common on iOS only.

iOS #

On iOS you can specify any number of buttons. Each button can optionally +specify a style, which is one of 'default', 'cancel' or 'destructive'.

Android #

On Android at most three buttons can be specified. Android has a concept +of a neutral, negative and a positive button:

  • If you specify one button, it will be the 'positive' one (such as 'OK')
  • Two buttons mean 'negative', 'positive' (such as 'Cancel', 'OK')
  • Three buttons mean 'neutral', 'negative', 'positive' (such as 'Later', 'Cancel', 'OK')

By default alerts on Android can be dismissed by tapping outside of the alert +box. This event can be handled by providing an optional options parameter, +with an onDismiss callback property { onDismiss: () => {} }.

Alternatively, the dismissing behavior can be disabled altogether by providing +an optional options parameter with the cancelable property set to false +i.e. { cancelable: false }

Example usage:

// Works on both iOS and Android +Alert.alert( + 'Alert Title', + 'My Alert Msg', + [ + {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')}, + {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, + {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!

\ No newline at end of file diff --git a/releases/0.47/docs/alertios.html b/releases/0.47/docs/alertios.html new file mode 100644 index 00000000000..c4b9b02ccd1 --- /dev/null +++ b/releases/0.47/docs/alertios.html @@ -0,0 +1,64 @@ +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.' +);

Creating an iOS prompt:

AlertIOS.prompt( + 'Enter a value', + null, + text => console.log("You entered "+text) +);

We recommend using the Alert.alert method for +cross-platform support if you don't need to create iOS-only prompts.

Methods #

static alert(title: string, message?: string, callbackOrButtons?: ?(() => void), ButtonsArray, type?: AlertType) #

Create and display a popup alert.

Parameters:
Name and TypeDescription
title

string

The dialog's title.

[message]

string

An optional message that appears below + the dialog's title.

[callbackOrButtons]

?(() => void) | ButtonsArray

This optional argument should + be either a single-argument function or an array of buttons. If passed + a function, it will be called when the user taps 'OK'.

If passed an array of button configurations, each button should include + a text key, as well as optional onPress and style keys. style + should be one of 'default', 'cancel' or 'destructive'.

[type]

Deprecated, do not use.


Example with custom buttons:
AlertIOS.alert( + 'Update available', + 'Keep your app up to date to enjoy the latest features', + [ + {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, + {text: 'Install', onPress: () => console.log('Install Pressed')}, + ], +);

static prompt(title: string, message?: string, callbackOrButtons?: ?((text: string) => void), ButtonsArray, type?: AlertType, defaultValue?: string, keyboardType?: string) #

Create and display a prompt to enter some text.

Parameters:
Name and TypeDescription
title

string

The dialog's title.

[message]

string

An optional message that appears above the text + input.

[callbackOrButtons]

?((text: string) => void) | ButtonsArray

This optional argument should + be either a single-argument function or an array of buttons. If passed + a function, it will be called with the prompt's value when the user + taps 'OK'.

If passed an array of button configurations, each button should include + a text key, as well as optional onPress and style keys (see + example). style should be one of 'default', 'cancel' or 'destructive'.

[type]

This configures the text input. One of 'plain-text', + 'secure-text' or 'login-password'.

[defaultValue]

string

The default text in text input.

[keyboardType]

string

The keyboard type of first text field(if exists). + One of 'default', 'email-address', 'numeric', 'phone-pad', + 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', + 'name-phone-pad', 'decimal-pad', 'twitter' or 'web-search'.


Example with custom buttons:
AlertIOS.prompt( + 'Enter password', + 'Enter your password to claim your $1.5B in lottery winnings', + [ + {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, + {text: 'OK', onPress: password => console.log('OK Pressed, password: ' + password)}, + ], + 'secure-text' +);

Example with the default button and a custom callback:
AlertIOS.prompt( + 'Update username', + null, + text => 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!

\ No newline at end of file diff --git a/releases/0.47/docs/android-building-from-source.html b/releases/0.47/docs/android-building-from-source.html new file mode 100644 index 00000000000..6ff24eaea82 --- /dev/null +++ b/releases/0.47/docs/android-building-from-source.html @@ -0,0 +1,49 @@ +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 { + classpath 'com.android.tools.build:gradle:1.3.1' + classpath 'de.undercouch:gradle-download-task:3.1.2' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +...

3. Adding the :ReactAndroid project #

Add the :ReactAndroid project in android/settings.gradle:

... +include ':ReactAndroid' + +project(':ReactAndroid').projectDir = new File( + rootProject.projectDir, '../node_modules/react-native/ReactAndroid') +...

Modify your android/app/build.gradle to use the :ReactAndroid project instead of the pre-compiled library, e.g. - replace compile 'com.facebook.react:react-native:+' with compile project(':ReactAndroid'):

... +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + compile 'com.android.support:appcompat-v7:23.0.1' + + compile project(':ReactAndroid') + + ... +} +...

4. Making 3rd-party modules use your fork #

If you use 3rd-party React Native modules, you need to override their dependencies so that they don't bundle the pre-compiled library. Otherwise you'll get an error while compiling - Error: more than one library with package name 'com.facebook.react'.

Modify your android/app/build.gradle, and add:

configurations.all { + exclude group: 'com.facebook.react', module: 'react-native' +}

Building from Android Studio #

From the Welcome screen of Android Studio choose "Import project" and select the android folder of your app.

You should be able to use the Run button to run your app on a device. Android Studio won't start the packager automatically, you'll need to start it by running npm start on the command line.

Additional notes #

Building from source can take a long time, especially for the first build, as it needs to download ~200 MB of artifacts and compile the native code. Every time you update the react-native version from your repo, the build directory may get deleted, and all the files are re-downloaded. To avoid this, you might want to change your build directory path by editing the ~/.gradle/init.gradle file:

gradle.projectsLoaded { + rootProject.allprojects { + buildDir = "/path/to/build/directory/${rootProject.name}/${project.name}" + } +}

Building for Maven/Nexus deployment #

If you find that you need to push up a locally compiled React Native .aar and related files to a remote Nexus repository, you can.

Start by following the Point Gradle to your Android SDK section of this page. Once you do this, assuming you have Gradle configured properly, you can then run the following command from the root of your React Native checkout to build and package all required files:

./gradlew ReactAndroid:installArchives

This will package everything that would typically be included in the android directory of your node_modules/react-native/ installation in the root directory of your React Native checkout.

Testing #

If you made changes to React Native and submit a pull request, all tests will run on your pull request automatically. To run the tests locally, see Running Tests.

Troubleshooting #

Gradle build fails in ndk-build. See the section about local.properties file above.

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

\ No newline at end of file diff --git a/releases/0.47/docs/android-ui-performance.html b/releases/0.47/docs/android-ui-performance.html new file mode 100644 index 00000000000..34cc423c798 --- /dev/null +++ b/releases/0.47/docs/android-ui-performance.html @@ -0,0 +1 @@ +Redirecting...

Redirecting...

Click here if you are not redirected. \ No newline at end of file diff --git a/releases/0.47/docs/animated.html b/releases/0.47/docs/animated.html new file mode 100644 index 00000000000..781d302e71a --- /dev/null +++ b/releases/0.47/docs/animated.html @@ -0,0 +1,166 @@ +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 +Animated.Value, hook it up to one or more style attributes of an animated +component, and then drive updates via animations using Animated.timing():

Animated.timing( // Animate value over time + this.state.fadeAnim, // The value to drive + { + toValue: 1, // Animate to final value of 1 + } +).start(); // Start the animation

Refer to the Animations guide to see +additional examples of Animated in action.

Overview #

There are two value types you can use with Animated:

Animated.Value can bind to style properties or other props, and can be +interpolated as well. A single Animated.Value can drive any number of +properties.

Configuring animations #

Animated provides three types of animation types. Each animation type +provides a particular animation curve that controls how your values animate +from their initial value to the final value:

In most cases, you will be using timing(). By default, it uses a symmetric +easeInOut curve that conveys the gradual acceleration of an object to full +speed and concludes by gradually decelerating to a stop.

Working with animations #

Animations are started by calling start() on your animation. start() +takes a completion callback that will be called when the animation is done. +If the animation finished running normally, the completion callback will be +invoked with {finished: true}. If the animation is done because stop() +was called on it before it could finish (e.g. because it was interrupted by a +gesture or another animation), then it will receive {finished: false}.

Using the native driver #

By using the native driver, we send everything about the animation to native +before starting the animation, allowing native code to perform the animation +on the UI thread without having to go through the bridge on every frame. +Once the animation has started, the JS thread can be blocked without +affecting the animation.

You can use the native driver by specifying useNativeDriver: true in your +animation configuration. See the +Animations guide to learn +more.

Animatable components #

Only animatable components can be animated. These special components do the +magic of binding the animated values to the properties, and do targeted +native updates to avoid the cost of the react render and reconciliation +process on every frame. They also handle cleanup on unmount so they are safe +by default.

Animated exports the following animatable components using the above +wrapper:

  • Animated.Image
  • Animated.ScrollView
  • Animated.Text
  • Animated.View

Composing animations #

Animations can also be combined in complex ways using composition functions:

Animations can also be chained together simply by setting the toValue of +one animation to be another Animated.Value. See +Tracking dynamic values in +the Animations guide.

By default, if one animation is stopped or interrupted, then all other +animations in the group are also stopped.

Combining animated values #

You can combine two animated values via addition, multiplication, division, +or modulo to make a new animated value:

Interpolation #

The interpolate() function allows input ranges to map to different output +ranges. By default, it will extrapolate the curve beyond the ranges given, +but you can also have it clamp the output value. It uses lineal interpolation +by default but also supports easing functions.

Read more about interpolation in the +Animation guide.

Handling gestures and other events #

Gestures, like panning or scrolling, and other events can map directly to +animated values using Animated.event(). This is done with a structured map +syntax so that values can be extracted from complex event objects. The first +level is an array to allow mapping across multiple args, and that array +contains nested objects.

For example, when working with horizontal scrolling gestures, you would do +the following in order to map event.nativeEvent.contentOffset.x to +scrollX (an Animated.Value):

onScroll={Animated.event( + // scrollX = e.nativeEvent.contentOffset.x + [{ nativeEvent: { + contentOffset: { + x: scrollX + } + } + }] + )}

Methods #

static decay(value, config) #

Animates a value from an initial velocity to zero based on a decay +coefficient.

Config is an object that may have the following options:

  • velocity: Initial velocity. Required.
  • deceleration: Rate of decay. Default 0.997.
  • useNativeDriver: Uses the native driver when true. Default false.

static timing(value, config) #

Animates a value along a timed easing curve. The +Easing module has tons of predefined curves, or you +can use your own function.

Config is an object that may have the following options:

  • duration: Length of animation (milliseconds). Default 500.
  • easing: Easing function to define curve. +Default is Easing.inOut(Easing.ease).
  • delay: Start the animation after delay (milliseconds). Default 0.
  • useNativeDriver: Uses the native driver when true. Default false.

static spring(value, config) #

Spring animation based on Rebound and +Origami. Tracks velocity state to +create fluid motions as the toValue updates, and can be chained together.

Config is an object that may have the following options. Note that you can +only define bounciness/speed or tension/friction but not both:

  • friction: Controls "bounciness"/overshoot. Default 7.
  • tension: Controls speed. Default 40.
  • speed: Controls speed of the animation. Default 12.
  • bounciness: Controls bounciness. Default 8.
  • useNativeDriver: Uses the native driver when true. Default false.

static add(a, b) #

Creates a new Animated value composed from two Animated values added +together.

static divide(a, b) #

Creates a new Animated value composed by dividing the first Animated value +by the second Animated value.

static multiply(a, b) #

Creates a new Animated value composed from two Animated values multiplied +together.

static modulo(a, modulus) #

Creates a new Animated value that is the (non-negative) modulo of the +provided Animated value

static diffClamp(a, min, max) #

Create a new Animated value that is limited between 2 values. It uses the +difference between the last value so even if the value is far from the bounds +it will start changing when the value starts getting closer again. +(value = clamp(value + diff, min, max)).

This is useful with scroll events, for example, to show the navbar when +scrolling up and to hide it when scrolling down.

static delay(time) #

Starts an animation after the given delay.

static sequence(animations) #

Starts an array of animations in order, waiting for each to complete +before starting the next. If the current running animation is stopped, no +following animations will be started.

static parallel(animations, config?) #

Starts an array of animations all at the same time. By default, if one +of the animations is stopped, they will all be stopped. You can override +this with the stopTogether flag.

static stagger(time, animations) #

Array of animations may run in parallel (overlap), but are started in +sequence with successive delays. Nice for doing trailing effects.

static loop(animation) #

Loops a given animation continuously, so that each time it reaches the +end, it resets and begins again from the start. Can specify number of +times to loop using the key 'iterations' in the config. Will loop without +blocking the UI thread if the child animation is set to 'useNativeDriver'.

static event(argMapping, config?) #

Takes an array of mappings and extracts values from each arg accordingly, +then calls setValue on the mapped outputs. e.g.

onScroll={Animated.event( + [{nativeEvent: {contentOffset: {x: this._scrollX}}}] + {listener}, // Optional async listener + ) + ... + onPanResponderMove: Animated.event([ + null, // raw event arg ignored + {dx: this._panX}, // gestureState arg + ]),

Config is an object that may have the following options:

  • listener: Optional async listener.
  • useNativeDriver: Uses the native driver when true. Default false.

static createAnimatedComponent(Component) #

Make any React component Animatable. Used to create Animated.View, etc.

static attachNativeEvent(viewRef, eventName, argMapping) #

Imperative API to attach an animated value to an event on a view. Prefer using +Animated.event with useNativeDrive: true if possible.

static forkEvent(event, listener) #

Advanced imperative API for snooping on animated events that are passed in through props. Use +values directly where possible.

static unforkEvent(event, listener) #

Properties #

Value: AnimatedValue #

Standard value class for driving animations. Typically initialized with +new Animated.Value(0);

See also AnimatedValue.

ValueXY: AnimatedValueXY #

2D value class for driving 2D animations, such as pan gestures.

See also AnimatedValueXY.

Interpolation: AnimatedInterpolation #

exported to use the Interpolation type in flow

See also AnimatedInterpolation.

class AnimatedValue #

    Standard value for driving animations. One Animated.Value can drive +multiple properties in a synchronized fashion, but can only be driven by one +mechanism at a time. Using a new mechanism (e.g. starting a new animation, +or calling setValue) will stop any previous ones.

    Methods #

    constructor(value) #

    setValue(value) #

    Directly set the value. This will stop any animations running on the value +and update all the bound properties.

    setOffset(offset) #

    Sets an offset that is applied on top of whatever value is set, whether via +setValue, an animation, or Animated.event. Useful for compensating +things like the start of a pan gesture.

    flattenOffset() #

    Merges the offset value into the base value and resets the offset to zero. +The final output of the value is unchanged.

    extractOffset() #

    Sets the offset value to the base value, and resets the base value to zero. +The final output of the value is unchanged.

    addListener(callback) #

    Adds an asynchronous listener to the value so you can observe updates from +animations. This is useful because there is no way to +synchronously read the value because it might be driven natively.

    removeListener(id) #

    removeAllListeners() #

    stopAnimation(callback?) #

    Stops any running animation or tracking. callback is invoked with the +final value after stopping the animation, which is useful for updating +state to match the animation position with layout.

    resetAnimation(callback?) #

    Stops any animation and resets the value to its original

    interpolate(config) #

    Interpolates the value before updating the property, e.g. mapping 0-1 to +0-10.

    animate(animation, callback) #

    Typically only used internally, but could be used by a custom Animation +class.

    stopTracking() #

    Typically only used internally.

    track(tracking) #

    Typically only used internally.

class AnimatedValueXY #

    2D Value for driving 2D animations, such as pan gestures. Almost identical +API to normal Animated.Value, but multiplexed. Contains two regular +Animated.Values under the hood.

    Example #

    class DraggableView extends React.Component { + constructor(props) { + super(props); + this.state = { + pan: new Animated.ValueXY(), // inits to zero + }; + this.state.panResponder = PanResponder.create({ + onStartShouldSetPanResponder: () => true, + onPanResponderMove: Animated.event([null, { + dx: this.state.pan.x, // x,y are Animated.Value + dy: this.state.pan.y, + }]), + onPanResponderRelease: () => { + Animated.spring( + this.state.pan, // Auto-multiplexed + {toValue: {x: 0, y: 0}} // Back to zero + ).start(); + }, + }); + } + render() { + return ( + <Animated.View + {...this.state.panResponder.panHandlers} + style={this.state.pan.getLayout()}> + {this.props.children} + </Animated.View> + ); + } + }

    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!

\ No newline at end of file diff --git a/releases/0.47/docs/animations.html b/releases/0.47/docs/animations.html new file mode 100644 index 00000000000..0774d28617c --- /dev/null +++ b/releases/0.47/docs/animations.html @@ -0,0 +1,306 @@ +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:

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. +Then, an easing animation is started on the fadeAnim animated value, +which will update all of its dependent mappings (in this case, just the opacity) on each frame as the value animates to the final value of 1.

This is done in an optimized way that is faster than calling setState and re-rendering.
Because the entire configuration is declarative, we will be able to implement further optimizations that serialize the configuration and runs the animation on a high-priority thread.

Configuring animations #

Animations are heavily configurable. Custom and predefined easing functions, delays, durations, decay factors, spring constants, and more can all be tweaked depending on the type of animation.

Animated provides several animation types, the most commonly used one being Animated.timing(). +It supports animating a value over time using one of various predefined easing functions, or you can use your own. +Easing functions are typically used in animation to convey gradual acceleration and deceleration of objects.

By default, timing will use a easeInOut curve that conveys gradual acceleration to full speed and concludes by gradually decelerating to a stop. +You can specify a different easing function by passing a easing parameter. +Custom duration or even a delay before the animation starts is also supported.

For example, if we want to create a 2-second long animation of an object that slightly backs up before moving to its final position:

Animated.timing( + this.state.xPosition, + { + toValue: 100, + easing: Easing.back, + duration: 2000, + } +).start();

Take a look at the Configuring animations section of the Animated API reference to learn more about all the config parameters supported by the built-in animations.

Composing animations #

Animations can be combined and played in sequence or in parallel. +Sequential animations can play immediately after the previous animation has finished, +or they can start after a specified delay. +The Animated API provides several methods, such as sequence() and delay(), +each of which simply take an array of animations to execute and automatically calls start()/stop() as needed.

For example, the following animation coasts to a stop, then it springs back while twirling in parallel:

Animated.sequence([ // decay, then spring to start and twirl + Animated.decay(position, { // coast to a stop + velocity: {x: gestureState.vx, y: gestureState.vy}, // velocity from gesture release + deceleration: 0.997, + }), + Animated.parallel([ // after decay, in parallel: + Animated.spring(position, { + toValue: {x: 0, y: 0} // return to start + }), + Animated.timing(twirl, { // and twirl + toValue: 360, + }), + ]), +]).start(); // start the sequence group

If one animation is stopped or interrupted, then all other animations in the group are also stopped. +Animated.parallel has a stopTogether option that can be set to false to disable this.

You can find a full list of composition methods in the Composing animations section of the Animated API reference.

Combining animated values #

You can combine two animated values via addition, multiplication, division, or modulo to make a new animated value.

There are some cases where an animated value needs to invert another animated value for calculation. +An example is inverting a scale (2x --> 0.5x):

const a = Animated.Value(1); +const b = Animated.divide(1, a); + +Animated.spring(a, { + toValue: 2, +}).start();

Interpolation #

Each property can be run through an interpolation first. +An interpolation maps input ranges to output ranges, +typically using a linear interpolation but also supports easing functions. +By default, it will extrapolate the curve beyond the ranges given, but you can also have it clamp the output value.

A simple mapping to convert a 0-1 range to a 0-100 range would be:

value.interpolate({ + inputRange: [0, 1], + outputRange: [0, 100], +});

For example, you may want to think about your Animated.Value as going from 0 to 1, +but animate the position from 150px to 0px and the opacity from 0 to 1. +This can easily be done by modifying style from the example above like so:

style={{ + opacity: this.state.fadeAnim, // Binds directly + transform: [{ + translateY: this.state.fadeAnim.interpolate({ + inputRange: [0, 1], + outputRange: [150, 0] // 0 : 150, 0.5 : 75, 1 : 0 + }), + }], + }}

interpolate() supports multiple range segments as well, which is handy for defining dead zones and other handy tricks. +For example, to get an negation relationship at -300 that goes to 0 at -100, then back up to 1 at 0, and then back down to zero at 100 followed by a dead-zone that remains at 0 for everything beyond that, you could do:

value.interpolate({ + inputRange: [-300, -100, 0, 100, 101], + outputRange: [300, 0, 1, 0, 0], +});

Which would map like so:

Input | Output +------|------- + -400| 450 + -300| 300 + -200| 150 + -100| 0 + -50| 0.5 + 0| 1 + 50| 0.5 + 100| 0 + 101| 0 + 200| 0

interpolate() also supports mapping to strings, allowing you to animate colors as well as values with units. For example, if you wanted to animate a rotation you could do:

value.interpolate({ + inputRange: [0, 360], + outputRange: ['0deg', '360deg'] +})

interpolate() also supports arbitrary easing functions, many of which are already implemented in the +Easing module. +interpolate() also has configurable behavior for extrapolating the outputRange. +You can set the extrapolation by setting the extrapolate, extrapolateLeft, or extrapolateRight options. +The default value is extend but you can use clamp to prevent the output value from exceeding outputRange.

Tracking dynamic values #

Animated values can also track other values. +Just set the toValue of an animation to another animated value instead of a plain number. +For example, a "Chat Heads" animation like the one used by Messenger on Android could be implemented with a spring() pinned on another animated value, or with timing() and a duration of 0 for rigid tracking. +They can also be composed with interpolations:

Animated.spring(follower, {toValue: leader}).start(); +Animated.timing(opacity, { + toValue: pan.x.interpolate({ + inputRange: [0, 300], + outputRange: [1, 0], + }), +}).start();

The leader and follower animated values would be implemented using Animated.ValueXY(). +ValueXY is a handy way to deal with 2D interactions, such as panning or dragging. +It is a simple wrapper that basically contains two Animated.Value instances and some helper functions that call through to them, +making ValueXY a drop-in replacement for Value in many cases. +It allows us to track both x and y values in the example above.

Tracking gestures #

Gestures, like panning or scrolling, and other events can map directly to animated values using Animated.event. +This is done with a structured map syntax so that values can be extracted from complex event objects. +The first level is an array to allow mapping across multiple args, and that array contains nested objects.

For example, when working with horizontal scrolling gestures, +you would do the following in order to map event.nativeEvent.contentOffset.x to scrollX (an Animated.Value):

onScroll={Animated.event( + // scrollX = e.nativeEvent.contentOffset.x + [{ nativeEvent: { + contentOffset: { + x: scrollX + } + } + }] + )}

When using PanResponder, you could use the following code to extract the x and y positions from gestureState.dx and gestureState.dy. +We use a null in the first position of the array, as we are only interested in the second argument passed to the PanResponder handler, +which is the gestureState.

onPanResponderMove={Animated.event( + [null, // ignore the native event + // extract dx and dy from gestureState + // like 'pan.x = gestureState.dx, pan.y = gestureState.dy' + {dx: pan.x, dy: pan.y} +])}

Responding to the current animation value #

You may notice that there is no obvious way to read the current value while animating. +This is because the value may only be known in the native runtime due to optimizations. +If you need to run JavaScript in response to the current value, there are two approaches:

  • spring.stopAnimation(callback) will stop the animation and invoke callback with the final value. This is useful when making gesture transitions.
  • spring.addListener(callback) will invoke callback asynchronously while the animation is running, providing a recent value. +This is useful for triggering state changes, +for example snapping a bobble to a new option as the user drags it closer, +because these larger state changes are less sensitive to a few frames of lag compared to continuous gestures like panning which need to run at 60 fps.

Animated is designed to be fully serializable so that animations can be run in a high performance way, independent of the normal JavaScript event loop. +This does influence the API, so keep that in mind when it seems a little trickier to do something compared to a fully synchronous system. +Check out Animated.Value.addListener as a way to work around some of these limitations, +but use it sparingly since it might have performance implications in the future.

Using the native driver #

The Animated API is designed to be serializable. +By using the native driver, +we send everything about the animation to native before starting the animation, +allowing native code to perform the animation on the UI thread without having to go through the bridge on every frame. +Once the animation has started, the JS thread can be blocked without affecting the animation.

Using the native driver for normal animations is quite simple. +Just add useNativeDriver: true to the animation config when starting it.

Animated.timing(this.state.animatedValue, { + toValue: 1, + duration: 500, + useNativeDriver: true, // <-- Add this +}).start();

Animated values are only compatible with one driver so if you use native driver when starting an animation on a value, +make sure every animation on that value also uses the native driver.

The native driver also works with Animated.event. +This is specially useful for animations that follow the scroll position as without the native driver, +the animation will always run a frame behind the gesture due to the async nature of React Native.

<Animated.ScrollView // <-- Use the Animated ScrollView wrapper + scrollEventThrottle={1} // <-- Use 1 here to make sure no events are ever missed + onScroll={Animated.event( + [{ nativeEvent: { contentOffset: { y: this.state.animatedValue } } }], + { useNativeDriver: true } // <-- Add this + )} +> + {content} +</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. +The main limitation is that you can only animate non-layout properties: +things like transform and opacity 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 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 +especially useful when layout changes may affect ancestors, for example a "see +more" expansion that also increases the size of the parent and pushes down the +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);

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 +function before the next repaint. It is an essential building block for +animations that underlies all of the JavaScript-based animation APIs. In +general, you shouldn't need to call this yourself - the animation APIs will +manage frame updates for you.

setNativeProps #

As mentioned in the Direction Manipulation section, +setNativeProps allows us to modify properties of native-backed +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.

If you find your animations with dropping frames (performing below 60 frames +per second), look into using setNativeProps or shouldComponentUpdate to +optimize them. Or you could run the animations on the UI thread rather than +the JavaScript thread with the useNativeDriver +option. +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 diff --git a/releases/0.47/docs/appregistry.html b/releases/0.47/docs/appregistry.html new file mode 100644 index 00000000000..a4179ceae7c --- /dev/null +++ b/releases/0.47/docs/appregistry.html @@ -0,0 +1,44 @@ +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 +AppRegistry.runApplication.

To "stop" an application when a view should be destroyed, call +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 setWrapperComponentProvider(provider) #

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 + notified of this event and it may decide to destroy the JS context.

static startHeadlessTask(taskId, taskKey, data) #

Only called from native code. Starts a headless task.

@param taskId the native id for this task instance to keep track of its execution +@param taskKey the key for the task to start +@param data the data to pass to the task

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

\ No newline at end of file diff --git a/releases/0.47/docs/appstate.html b/releases/0.47/docs/appstate.html new file mode 100644 index 00000000000..d8ba68c0646 --- /dev/null +++ b/releases/0.47/docs/appstate.html @@ -0,0 +1,64 @@ +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 + foreground & background, and during periods of inactivity such as + entering the Multitasking view or in the event of an incoming call

For more information, see +Apple's documentation

Basic Usage #

To see the current state, you can check AppState.currentState, which +will be kept up-to-date. However, currentState will be null at launch +while AppState retrieves it over the bridge.

import React, {Component} from 'react' +import {AppState, Text} from 'react-native' + +class AppStateExample extends Component { + + state = { + appState: AppState.currentState + } + + componentDidMount() { + AppState.addEventListener('change', this._handleAppStateChange); + } + + componentWillUnmount() { + AppState.removeEventListener('change', this._handleAppStateChange); + } + + _handleAppStateChange = (nextAppState) => { + if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') { + console.log('App has come to the foreground!') + } + this.setState({appState: nextAppState}); + } + + render() { + return ( + <Text>Current state is: {this.state.appState}</Text> + ); + } + +}

This example will only ever appear to say "Current state is: active" because +the app is only visible to the user when in the active state, and the null +state will happen only momentarily.

Methods #

=(;, () #

addEventListener(type, handler) #

Add a handler to AppState changes by listening to the change event type +and providing the handler

TODO: now that AppState is a subclass of NativeEventEmitter, we could deprecate +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!

\ No newline at end of file diff --git a/releases/0.47/docs/asyncstorage.html b/releases/0.47/docs/asyncstorage.html new file mode 100644 index 00000000000..93416de0a31 --- /dev/null +++ b/releases/0.47/docs/asyncstorage.html @@ -0,0 +1,136 @@ +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 +serialized dictionary and larger values in separate files. On Android, +AsyncStorage will use either RocksDB or SQLite +based on what is available.

The AsyncStorage JavaScript code is a simple facade that provides a clear +JavaScript API, real Error objects, and simple non-multi functions. Each +method in the API returns a Promise object.

Persisting data:

try { + await AsyncStorage.setItem('@MySuperStore:key', 'I like to save it.'); +} catch (error) { + // Error saving data +}

Fetching data:

try { + const value = await AsyncStorage.getItem('@MySuperStore:key'); + if (value !== null){ + // We have data!! + console.log(value); + } +} catch (error) { + // Error retrieving data +}

Methods #

static getItem(key: string, callback?: ?(error: ?Error, result: ?string) => void) #

Fetches an item for a key and invokes a callback upon completion. +Returns a Promise object.

Parameters:
Name and TypeDescription
key

string

Key of the item to fetch.

[callback]

?(error: ?Error, result: ?string) => void

Function that will be called with a result if found or + any error.

static setItem(key: string, value: string, callback?: ?(error: ?Error) => void) #

Sets the value for a key and invokes a callback upon completion. +Returns a Promise object.

Parameters:
Name and TypeDescription
key

string

Key of the item to set.

value

string

Value to set for the key.

[callback]

?(error: ?Error) => void

Function that will be called with any error.

static removeItem(key: string, callback?: ?(error: ?Error) => void) #

Removes an item for a key and invokes a callback upon completion. +Returns a Promise object.

Parameters:
Name and TypeDescription
key

string

Key of the item to remove.

[callback]

?(error: ?Error) => void

Function that will be called with any error.

static mergeItem(key: string, value: string, callback?: ?(error: ?Error) => void) #

Merges an existing key value with an input value, assuming both values +are stringified JSON. Returns a Promise object.

NOTE: This is not supported by all native implementations.

Parameters:
Name and TypeDescription
key

string

Key of the item to modify.

value

string

New value to merge for the key.

[callback]

?(error: ?Error) => void

Function that will be called with any error.


Example:
+let UID123_object = { + name: 'Chris', + age: 30, + traits: {hair: 'brown', eyes: 'brown'}, +}; +// You only need to define what will be added or updated +let UID123_delta = { + age: 31, + traits: {eyes: 'blue', shoe_size: 10} +}; + +AsyncStorage.setItem('UID123', JSON.stringify(UID123_object), () => { + AsyncStorage.mergeItem('UID123', JSON.stringify(UID123_delta), () => { + AsyncStorage.getItem('UID123', (err, result) => { + console.log(result); + }); + }); +}); + +// Console log result: +// => {'name':'Chris','age':31,'traits': +// {'shoe_size':10,'hair':'brown','eyes':'blue'}}

static clear(callback?: ?(error: ?Error) => void) #

Erases all AsyncStorage for all clients, libraries, etc. You probably +don't want to call this; use removeItem or multiRemove to clear only +your app's keys. Returns a Promise object.

Parameters:
Name and TypeDescription
[callback]

?(error: ?Error) => void

Function that will be called with any error.

static getAllKeys(callback?: ?(error: ?Error, keys: ?Array<string>) => void) #

Gets all keys known to your app; for all callers, libraries, etc. +Returns a Promise object.

Parameters:
Name and TypeDescription
[callback]

?(error: ?Error, keys: ?Array<string>) => void

Function that will be called the keys found and any error.

static flushGetRequests() #

Flushes any pending requests using a single batch call to get the data.

static multiGet(keys: Array<string>, callback?: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void) #

This allows you to batch the fetching of items given an array of key +inputs. Your callback will be invoked with an array of corresponding +key-value pairs found:

multiGet(['k1', 'k2'], cb) -> cb([['k1', 'val1'], ['k2', 'val2']])

The method returns a Promise object.

Parameters:
Name and TypeDescription
keys

Array<string>

Array of key for the items to get.

[callback]

?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void

Function that will be called with a key-value array of + the results, plus an array of any key-specific errors found.


Example:
AsyncStorage.getAllKeys((err, keys) => { + AsyncStorage.multiGet(keys, (err, stores) => { + stores.map((result, i, store) => { + // get at each store's key/value so you can work with it + let key = store[i][0]; + let value = store[i][1]; + }); + }); +});

static multiSet(keyValuePairs: Array<Array<string>>, callback?: ?(errors: ?Array<Error>) => void) #

Use this as a batch operation for storing multiple key-value pairs. When +the operation completes you'll get a single callback with any errors:

multiSet([['k1', 'val1'], ['k2', 'val2']], cb);

The method returns a Promise object.

Parameters:
Name and TypeDescription
keyValuePairs

Array<Array<string>>

Array of key-value array for the items to set.

[callback]

?(errors: ?Array<Error>) => void

Function that will be called with an array of any + key-specific errors found.

static multiRemove(keys: Array<string>, callback?: ?(errors: ?Array<Error>) => void) #

Call this to batch the deletion of all keys in the keys array. Returns +a Promise object.

Parameters:
Name and TypeDescription
keys

Array<string>

Array of key for the items to delete.

[callback]

?(errors: ?Array<Error>) => void

Function that will be called an array of any key-specific + errors found.


Example:
+let keys = ['k1', 'k2']; +AsyncStorage.multiRemove(keys, (err) => { + // keys k1 & k2 removed, if they existed + // do most stuff after removal (if you want) +});

static multiMerge(keyValuePairs: Array<Array<string>>, callback?: ?(errors: ?Array<Error>) => void) #

Batch operation to merge in existing and new values for a given set of +keys. This assumes that the values are stringified JSON. Returns a +Promise object.

NOTE: This is not supported by all native implementations.

Parameters:
Name and TypeDescription
keyValuePairs

Array<Array<string>>

Array of key-value array for the items to merge.

[callback]

?(errors: ?Array<Error>) => void

Function that will be called with an array of any + key-specific errors found.


Example:
+// first user, initial values +let UID234_object = { + name: 'Chris', + age: 30, + traits: {hair: 'brown', eyes: 'brown'}, +}; + +// first user, delta values +let UID234_delta = { + age: 31, + traits: {eyes: 'blue', shoe_size: 10}, +}; + +// second user, initial values +let UID345_object = { + name: 'Marge', + age: 25, + traits: {hair: 'blonde', eyes: 'blue'}, +}; + +// second user, delta values +let UID345_delta = { + age: 26, + traits: {eyes: 'green', shoe_size: 6}, +}; + +let multi_set_pairs = [['UID234', JSON.stringify(UID234_object)], ['UID345', JSON.stringify(UID345_object)]] +let multi_merge_pairs = [['UID234', JSON.stringify(UID234_delta)], ['UID345', JSON.stringify(UID345_delta)]] + +AsyncStorage.multiSet(multi_set_pairs, (err) => { + AsyncStorage.multiMerge(multi_merge_pairs, (err) => { + AsyncStorage.multiGet(['UID234','UID345'], (err, stores) => { + stores.map( (result, i, store) => { + let key = store[i][0]; + let val = store[i][1]; + console.log(key, val); + }); + }); + }); +}); + +// 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!

\ No newline at end of file diff --git a/releases/0.47/docs/backandroid.html b/releases/0.47/docs/backandroid.html new file mode 100644 index 00000000000..0291cec088d --- /dev/null +++ b/releases/0.47/docs/backandroid.html @@ -0,0 +1,19 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/backhandler.html b/releases/0.47/docs/backhandler.html new file mode 100644 index 00000000000..e5579e4b815 --- /dev/null +++ b/releases/0.47/docs/backhandler.html @@ -0,0 +1,32 @@ +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), +and if one subscription returns true then subscriptions registered earlier will not be called.

Example:

BackHandler.addEventListener('hardwareBackPress', function() { + // this.onMainScreen and this.goBack are just examples, you need to use your own implementation here + // Typically you would use the navigator here to go to the last state. + + if (!this.onMainScreen()) { + this.goBack(); + return true; + } + return false; +});

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 diff --git a/releases/0.47/docs/building-for-apple-tv.html b/releases/0.47/docs/building-for-apple-tv.html new file mode 100644 index 00000000000..a8d077eaa0c --- /dev/null +++ b/releases/0.47/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/releases/0.47/docs/button.html b/releases/0.47/docs/button.html new file mode 100644 index 00000000000..76595d27e2c --- /dev/null +++ b/releases/0.47/docs/button.html @@ -0,0 +1,31 @@ +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 +button using TouchableOpacity +or TouchableNativeFeedback. +For inspiration, look at the source code for this button component. +Or, take a look at the wide variety of button components built by the community.

Example usage:

<Button + onPress={onPressLearnMore} + title="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!

\ No newline at end of file diff --git a/releases/0.47/docs/cameraroll.html b/releases/0.47/docs/cameraroll.html new file mode 100644 index 00000000000..238c000db07 --- /dev/null +++ b/releases/0.47/docs/cameraroll.html @@ -0,0 +1,27 @@ +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. +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!

\ No newline at end of file diff --git a/releases/0.47/docs/clipboard.html b/releases/0.47/docs/clipboard.html new file mode 100644 index 00000000000..7777ddd85e2 --- /dev/null +++ b/releases/0.47/docs/clipboard.html @@ -0,0 +1,23 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/colors.html b/releases/0.47/docs/colors.html new file mode 100644 index 00000000000..76a78bc865c --- /dev/null +++ b/releases/0.47/docs/colors.html @@ -0,0 +1,19 @@ +Color Reference

Color Reference #

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 diff --git a/releases/0.47/docs/communication-ios.html b/releases/0.47/docs/communication-ios.html new file mode 100644 index 00000000000..2f9444c7301 --- /dev/null +++ b/releases/0.47/docs/communication-ios.html @@ -0,0 +1,95 @@ +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}; + +RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge + moduleName:@"ImageBrowserApp" + initialProperties:props];
'use strict'; + +import React from 'react'; +import { + AppRegistry, + View, + Image +} from 'react-native'; + +class ImageBrowserApp extends React.Component { + renderImage(imgURI) { + return ( + <Image source={{uri: imgURI}} /> + ); + } + render() { + return ( + <View> + {this.props.images.map(this.renderImage)} + </View> + ); + } +} + +AppRegistry.registerComponent('AwesomeProject', () => ImageBrowserApp);

RCTRootView also provides a read-write property appProperties. After appProperties is set, the React Native app is re-rendered with new properties. The update is only performed when the new updated properties differ from the previous ones.

NSArray *imageList = @[@"http://foo.com/bar3.png", + @"http://foo.com/bar4.png"]; + +rootView.appProperties = @{@"images" : imageList};

It is fine to update properties anytime. However, updates have to be performed on the main thread. You use the getter on any thread.

There is no way to update only a few properties at a time. We suggest that you build it into your own wrapper instead.

Note: +Currently, JS functions componentWillReceiveProps and componentWillUpdateProps of the top level RN component will not be called after a prop update. However, you can access the new props in componentWillMount function.

Passing properties from React Native to native #

The problem exposing properties of native components is covered in detail in this article. In short, export properties with RCT_CUSTOM_VIEW_PROPERTY macro in your custom native component, then just use them in React Native as if the component was an ordinary React Native component.

Limits of properties #

The main drawback of cross-language properties is that they do not support callbacks, which would allow us to handle bottom-up data bindings. Imagine you have a small RN view that you want to be removed from the native parent view as a result of a JS action. There is no way to do that with props, as the information would need to go bottom-up.

Although we have a flavor of cross-language callbacks (described here), these callbacks are not always the thing we need. The main problem is that they are not intended to be passed as properties. Rather, this mechanism allows us to trigger a native action from JS, and handle the result of that action in JS.

Other ways of cross-language interaction (events and native modules) #

As stated in the previous chapter, using properties comes with some limitations. Sometimes properties are not enough to drive the logic of our app and we need a solution that gives more flexibility. This chapter covers other communication techniques available in React Native. They can be used for internal communication (between JS and native layers in RN) as well as for external communication (between RN and the 'pure native' part of your app).

React Native enables you to perform cross-language function calls. You can execute custom native code from JS and vice versa. Unfortunately, depending on the side we are working on, we achieve the same goal in different ways. For native - we use events mechanism to schedule an execution of a handler function in JS, while for React Native we directly call methods exported by native modules.

Calling React Native functions from native (events) #

Events are described in detail in this article. Note that using events gives us no guarantees about execution time, as the event is handled on a separate thread.

Events are powerful, because they allow us to change React Native components without needing a reference to them. However, there are some pitfalls that you can fall into while using them:

  • As events can be sent from anywhere, they can introduce spaghetti-style dependencies into your project.
  • Events share namespace, which means that you may encounter some name collisions. Collisions will not be detected statically, which makes them hard to debug.
  • If you use several instances of the same React Native component and you want to distinguish them from the perspective of your event, you'll likely need to introduce identifiers and pass them along with events (you can use the native view's reactTag as an identifier).

The common pattern we use when embedding native in React Native is to make the native component's RCTViewManager a delegate for the views, sending events back to JavaScript via the bridge. This keeps related event calls in one place.

Calling native functions from React Native (native modules) #

Native modules are Objective-C classes that are available in JS. Typically one instance of each module is created per JS bridge. They can export arbitrary functions and constants to React Native. They have been covered in detail in this article.

The fact that native modules are singletons limits the mechanism in the context of embedding. Let's say we have a React Native component embedded in a native view and we want to update the native, parent view. Using the native module mechanism, we would export a function that not only takes expected arguments, but also an identifier of the parent native view. The identifier would be used to retrieve a reference to the parent view to update. That said, we would need to keep a mapping from identifiers to native views in the module.

Although this solution is complex, it is used in RCTUIManager, which is an internal React Native class that manages all React Native views.

Native modules can also be used to expose existing native libraries to JS. The Geolocation library is a living example of the idea.

Warning: +All native modules share the same namespace. Watch out for name collisions when creating new ones.

Layout computation flow #

When integrating native and React Native, we also need a way to consolidate two different layout systems. This section covers common layout problems and provides a brief description of mechanisms to address them.

Layout of a native component embedded in React Native #

This case is covered in this article. Basically, as all our native react views are subclasses of UIView, most style and size attributes will work like you would expect out of the box.

Layout of a React Native component embedded in native #

React Native content with fixed size #

The simplest scenario is when we have a React Native app with a fixed size, which is known to the native side. In particular, a full-screen React Native view falls into this case. If we want a smaller root view, we can explicitly set RCTRootView's frame.

For instance, to make an RN app 200 (logical) pixels high, and the hosting view's width wide, we could do:

// SomeViewController.m + +- (void)viewDidLoad +{ + [...] + RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge + moduleName:appName + initialProperties:props]; + rootView.frame = CGRectMake(0, 0, self.view.width, 200); + [self.view addSubview:rootView]; +}

When we have a fixed size root view, we need to respect its bounds on the JS side. In other words, we need to ensure that the React Native content can be contained within the fixed-size root view. The easiest way to ensure this is to use flexbox layout. If you use absolute positioning, and React components are visible outside the root view's bounds, you'll get overlap with native views, causing some features to behave unexpectedly. For instance, 'TouchableHighlight' will not highlight your touches outside the root view's bounds.

It's totally fine to update root view's size dynamically by re-setting its frame property. React Native will take care of the content's layout.

React Native content with flexible size #

In some cases we'd like to render content of initially unknown size. Let's say the size will be defined dynamically in JS. We have two solutions to this problem.

  1. You can wrap your React Native view in a ScrollView component. This guarantees that your content will always be available and it won't overlap with native views.
  2. React Native allows you to determine, in JS, the size of the RN app and provide it to the owner of the hosting RCTRootView. The owner is then responsible for re-laying out the subviews and keeping the UI consistent. We achieve this with RCTRootView's flexibility modes.

RCTRootView supports 4 different size flexibility modes:

// RCTRootView.h + +typedef NS_ENUM(NSInteger, RCTRootViewSizeFlexibility) { + RCTRootViewSizeFlexibilityNone = 0, + RCTRootViewSizeFlexibilityWidth, + RCTRootViewSizeFlexibilityHeight, + RCTRootViewSizeFlexibilityWidthAndHeight, +};

RCTRootViewSizeFlexibilityNone is the default value, which makes a root view's size fixed (but it still can be updated with setFrame:). The other three modes allow us to track React Native content's size updates. For instance, setting mode to RCTRootViewSizeFlexibilityHeight will cause React Native to measure the content's height and pass that information back to RCTRootView's delegate. An arbitrary action can be performed within the delegate, including setting the root view's frame, so the content fits. The delegate is called only when the size of the content has changed.

Warning: +Making a dimension flexible in both JS and native leads to undefined behavior. For example - don't make a top-level React component's width flexible (with flexbox) while you're using RCTRootViewSizeFlexibilityWidth on the hosting RCTRootView.

Let's look at an example.

// FlexibleSizeExampleView.m + +- (instancetype)initWithFrame:(CGRect)frame +{ + [...] + + _rootView = [[RCTRootView alloc] initWithBridge:bridge + moduleName:@"FlexibilityExampleApp" + initialProperties:@{}]; + + _rootView.delegate = self; + _rootView.sizeFlexibility = RCTRootViewSizeFlexibilityHeight; + _rootView.frame = CGRectMake(0, 0, self.frame.size.width, 0); +} + +#pragma mark - RCTRootViewDelegate +- (void)rootViewDidChangeIntrinsicSize:(RCTRootView *)rootView +{ + CGRect newFrame = rootView.frame; + 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 diff --git a/releases/0.47/docs/components-and-apis.html b/releases/0.47/docs/components-and-apis.html new file mode 100644 index 00000000000..6f04767a057 --- /dev/null +++ b/releases/0.47/docs/components-and-apis.html @@ -0,0 +1,209 @@ +Components and APIs

Components and APIs #

React Native provides a number of built-in components. You will find a full list of components and APIs on the sidebar to the left. If you're not sure where to get started, take a look at the following categories:

You're not limited to the components and APIs bundled with React Native. React Native is a community of thousands of developers. If you're looking for a library that does something specific, search the npm registry for packages mentioning react-native, or check out Awesome React Native for a curated list.

Basic Components #

Most apps will end up using one of these basic components. You'll want to get yourself familiarized with all of these if you're new to React Native.

+
+

View

+

The most fundamental component for building a UI.

+
+
+

Text

+

A component for displaying text.

+
+
+

Image

+

A component for displaying images.

+
+
+

TextInput

+

A component for inputting text into the app via a keyboard.

+
+
+

ScrollView

+

Provides a scrolling container that can host multiple components and views.

+
+
+

Button

+

A basic button component for handling touches that should render nicely on any platform.

+
+
+ +

User Interface #

Render common user interface controls on any platform using the following components. For platform specific components, keep reading.

+
+

Picker

+

Renders the native picker component on iOS and Android.

+
+
+

Slider

+

A component used to select a single value from a range of values.

+
+
+

Switch

+

Renders a boolean input.

+
+
+ +

List Views #

Unlike the more generic ScrollView, the following list view components only render elements that are currently showing on the screen. This makes them a great choice for displaying long lists of data.

+
+

FlatList

+

A component for rendering performant scrollable lists.

+
+
+

SectionList

+

Like FlatList, but for sectioned lists.

+
+
+ +

iOS Components and APIs #

Many of the following components provide wrappers for commonly used UIKit classes.

+
+

ActionSheetIOS

+

API to display an iOS action sheet or share sheet.

+
+
+

AdSupportIOS

+

API to access the "advertising identifier" on iOS.

+
+
+

AlertIOS

+

Create an iOS alert dialog with a message or create a prompt for user input.

+
+
+

DatePickerIOS

+

Renders a date/time picker (selector) on iOS.

+
+
+

ImagePickerIOS

+

Renders a image picker on iOS.

+
+
+

NavigatorIOS

+

A wrapper around UINavigationController, enabling you to implement a navigation stack.

+
+
+

ProgressViewIOS

+

Renders a UIProgressView on iOS.

+
+
+

PushNotificationIOS

+

Handle push notifications for your app, including permission handling and icon badge number.

+
+
+

SegmentedControlIOS

+

Renders a UISegmentedControl on iOS.

+
+
+

TabBarIOS

+

Renders a UITabViewController on iOS. Use with TabBarIOS.Item.

+
+
+ +

Android Components and APIs #

Many of the following components provide wrappers for commonly used Android classes.

+
+

BackHandler

+

Detect hardware button presses for back navigation.

+
+
+

DatePickerAndroid

+

Opens the standard Android date picker dialog.

+
+
+

DrawerLayoutAndroid

+

Renders a DrawerLayout on Android.

+
+
+

PermissionsAndroid

+

Provides access to the permissions model introduced in Android M.

+
+
+

ProgressBarAndroid

+

Renders a ProgressBar on Android.

+
+
+

TimePickerAndroid

+

Opens the standard Android time picker dialog.

+
+
+

ToastAndroid

+

Create an Android Toast alert.

+
+
+

ToolbarAndroid

+

Renders a Toolbar on Android.

+
+
+

ViewPagerAndroid

+

Container that allows to flip left and right between child views.

+
+
+ + +

Others #

These components may come in handy for certain applications. For an exhaustive list of components and APIs, check out the sidebar to the left.

+
+

ActivityIndicator

+

Displays a circular loading indicator.

+
+
+

Alert

+

Launches an alert dialog with the specified title and message.

+
+
+

CameraRoll

+

Provides access to the local camera roll / gallery.

+
+
+

Clipboard

+

Provides an interface for setting and getting content from the clipboard on both iOS and Android.

+
+
+

Dimensions

+

Provides an interface for getting device dimensions.

+
+
+

KeyboardAvoidingView

+

Provides a view that moves out of the way of the virtual keyboard automatically.

+
+
+

Linking

+

Provides a general interface to interact with both incoming and outgoing app links.

+
+
+

Modal

+

Provides a simple way to present content above an enclosing view.

+
+
+

PixelRatio

+

Provides access to the device pixel density.

+
+
+

RefreshControl

+

This component is used inside a ScrollView to add pull to refresh functionality.

+
+
+

StatusBar

+

Component to control the app status bar.

+
+
+

StyleSheet

+

Provides an abstraction layer similar to CSS stylesheets.

+
+
+

WebView

+

A component that renders web content in a native view.

+
+
+

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

\ No newline at end of file diff --git a/releases/0.47/docs/datepickerandroid.html b/releases/0.47/docs/datepickerandroid.html new file mode 100644 index 00000000000..000e4e7e12f --- /dev/null +++ b/releases/0.47/docs/datepickerandroid.html @@ -0,0 +1,34 @@ +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. + date: new Date(2020, 4, 25) + }); + if (action !== DatePickerAndroid.dismissedAction) { + // Selected year, month (0-11), day + } +} 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) - 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!

\ No newline at end of file diff --git a/releases/0.47/docs/datepickerios.html b/releases/0.47/docs/datepickerios.html new file mode 100644 index 00000000000..f040942e7c6 --- /dev/null +++ b/releases/0.47/docs/datepickerios.html @@ -0,0 +1,27 @@ +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?: 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?: 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!

\ No newline at end of file diff --git a/releases/0.47/docs/debugging.html b/releases/0.47/docs/debugging.html new file mode 100644 index 00000000000..6bf59138686 --- /dev/null +++ b/releases/0.47/docs/debugging.html @@ -0,0 +1,50 @@ +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; +import com.facebook.react.modules.network.OkHttpClientProvider; +import com.facebook.stetho.okhttp3.StethoInterceptor; +import java.util.concurrent.TimeUnit;
  3. In android/app/src/main/java/com/{yourAppName}/MainApplication.java add the function:

    public void onCreate() { + super.onCreate(); + Stetho.initializeWithDefaults(this); + OkHttpClient client = new OkHttpClient.Builder() + .connectTimeout(0, TimeUnit.MILLISECONDS) + .readTimeout(0, TimeUnit.MILLISECONDS) + .writeTimeout(0, TimeUnit.MILLISECONDS) + .cookieJar(new ReactCookieJarContainer()) + .addNetworkInterceptor(new StethoInterceptor()) + .build(); + OkHttpClientProvider.replaceOkHttpClient(client); +}
  4. Run react-native run-android

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

Debugging native code #

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

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

\ No newline at end of file diff --git a/releases/0.47/docs/dimensions.html b/releases/0.47/docs/dimensions.html new file mode 100644 index 00000000000..9fd4ef3d4b1 --- /dev/null +++ b/releases/0.47/docs/dimensions.html @@ -0,0 +1,29 @@ +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 +these constants should try to call this function on every render, rather +than caching the value (for example, using inline styles rather than +setting a value in a StyleSheet).

Example: var {height, width} = Dimensions.get('window');

@param {string} dim Name of dimension as defined when calling set. +@returns {Object?} Value for the dimension.

static addEventListener(type, handler) #

Add an event handler. Supported events:

  • change: Fires when a property within the Dimensions object changes. The argument +to the event handler is an object with window and screen properties whose values +are the same as the return values of Dimensions.get('window') and +Dimensions.get('screen'), respectively.

static removeEventListener(type, handler) #

Remove an event handler.

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

\ No newline at end of file diff --git a/releases/0.47/docs/direct-manipulation.html b/releases/0.47/docs/direct-manipulation.html new file mode 100644 index 00000000000..d65df2beafc --- /dev/null +++ b/releases/0.47/docs/direct-manipulation.html @@ -0,0 +1,171 @@ +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 +apps. setNativeProps is the React Native equivalent to setting +properties directly on a DOM node.

Use setNativeProps when frequent re-rendering creates a performance bottleneck

Direct manipulation will not be a tool that you reach for +frequently; you will typically only be using it for creating +continuous animations to avoid the overhead of rendering the component +hierarchy and reconciling many views. setNativeProps is imperative +and stores state in the native layer (DOM, UIView, etc.) and not +within your React components, which makes your code more difficult to +reason about. Before you use it, try to solve your problem with setState +and shouldComponentUpdate.

setNativeProps with TouchableOpacity #

TouchableOpacity +uses setNativeProps internally to update the opacity of its child +component:

setOpacityTo(value) { + // Redacted: animation related code + this.refs[CHILD_REF].setNativeProps({ + opacity: value + }); +},

This allows us to write the following code and know that the child will +have its opacity updated in response to taps, without the child having +any knowledge of that fact or requiring any changes to its implementation:

<TouchableOpacity onPress={this._handlePress}> + <View style={styles.button}> + <Text>Press me!</Text> + </View> +</TouchableOpacity>

Let's imagine that setNativeProps was not available. One way that we +might implement it with that constraint is to store the opacity value +in the state, then update that value whenever onPress is fired:

constructor(props) { + super(props); + this.state = { myButtonOpacity: 1, }; +} + +render() { + return ( + <TouchableOpacity onPress={() => this.setState({myButtonOpacity: 0.5})} + onPressOut={() => this.setState({myButtonOpacity: 1})}> + <View style={[styles.button, {opacity: this.state.myButtonOpacity}]}> + <Text>Press me!</Text> + </View> + </TouchableOpacity> + ) +}

This is computationally intensive compared to the original example - +React needs to re-render the component hierarchy each time the opacity +changes, even though other properties of the view and its children +haven't changed. Usually this overhead isn't a concern but when +performing continuous animations and responding to gestures, judiciously +optimizing your components can improve your animations' fidelity.

If you look at the implementation of setNativeProps in +NativeMethodsMixin.js +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:

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 +define a component with React.createClass you would not expect to be +able to set a style prop on it and have that work - you would need to +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.

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 +to depending on setNativeProps on its child, it also requires that the +child perform touch handling. To do this, it passes on various +props +that call back to the TouchableOpacity component. +TouchableHighlight, in contrast, is backed by a native view and only +requires that we implement setNativeProps.

setNativeProps to clear TextInput value #

Another very common use case of setNativeProps is to clear the value +of a TextInput. The controlled prop of TextInput can sometimes drop +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:

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.

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 +use setState instead of setNativeProps.

Other native methods #

The methods described here are available on most of the default components provided by React Native. Note, however, that they are not available on composite components that aren't directly backed by a native view. This will generally include most components that you define in your own app.

measure(callback) #

Determines the location on screen, width, and height of the given view and returns the values via an async callback. If successful, the callback will be called with the following arguments:

  • x
  • y
  • width
  • height
  • pageX
  • pageY

Note that these measurements are not available until after the rendering has been completed in native. If you need the measurements as soon as possible, consider using the onLayout prop instead.

measureInWindow(callback) #

Determines the location of the given view in the window and returns the values via an async callback. If the React root view is embedded in another native view, this will give you the absolute coordinates. If successful, the callback will be called with the following arguments:

  • x
  • y
  • width
  • height

measureLayout(relativeToNativeNode, onSuccess, onFail) #

Like measure(), but measures the view relative an ancestor, specified as relativeToNativeNode. This means that the returned x, y are relative to the origin x, y of the ancestor view.

As always, to obtain a native node handle for a component, you can use ReactNative.findNodeHandle(component).

focus() #

Requests focus for the given input or view. The exact behavior triggered will depend on the platform and type of view.

blur() #

Removes focus from an input or view. This is the opposite of focus().

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

\ No newline at end of file diff --git a/releases/0.47/docs/drawerlayoutandroid.html b/releases/0.47/docs/drawerlayoutandroid.html new file mode 100644 index 00000000000..e8631b73a52 --- /dev/null +++ b/releases/0.47/docs/drawerlayoutandroid.html @@ -0,0 +1,68 @@ +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 +side of the window specified by the drawerPosition prop and its width can +be set by the drawerWidth prop.

Example:

render: function() { + var navigationView = ( + <View style={{flex: 1, backgroundColor: '#fff'}}> + <Text style={{margin: 10, fontSize: 15, textAlign: 'left'}}>I'm in the Drawer!</Text> + </View> + ); + return ( + <DrawerLayoutAndroid + drawerWidth={300} + drawerPosition={DrawerLayoutAndroid.positions.Left} + renderNavigationView={() => navigationView}> + <View style={{flex: 1, alignItems: 'center'}}> + <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text> + <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>World!</Text> + </View> + </DrawerLayoutAndroid> + ); +},

Props #

drawerBackgroundColor?: color #

Specifies the background color of the drawer. The default value is white. +If you want to set the opacity of the drawer, use rgba. Example:

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

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?: 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?: 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?: 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 diff --git a/releases/0.47/docs/easing.html b/releases/0.47/docs/easing.html new file mode 100644 index 00000000000..5743e57ab02 --- /dev/null +++ b/releases/0.47/docs/easing.html @@ -0,0 +1,38 @@ +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 +following methods:

  • back provides a simple animation where the +object goes slightly back before moving forward
  • bounce provides a bouncing animation
  • ease provides a simple inertial animation
  • elastic provides a simple spring interaction

Standard functions #

Three standard easing functions are provided:

The poly function can be used to implement +quartic, quintic, and other higher power functions.

Additional functions #

Additional mathematical functions are provided by the following methods:

  • bezier provides a cubic bezier curve
  • circle provides a circular function
  • sin provides a sinusoidal function
  • exp provides an exponential function

The following helpers are used to modify other easing functions.

  • in runs an easing function forwards
  • inOut makes any easing function symmetrical
  • out runs an easing function backwards

Methods #

static step0(n) #

A stepping function, returns 1 for any positive value of n.

static step1(n) #

A stepping function, returns 1 if n is greater than or equal to 1.

static linear(t) #

A linear function, f(t) = t. Position correlates to elapsed time one to +one.

http://cubic-bezier.com/#0,0,1,1

static ease(t) #

A simple inertial interaction, similar to an object slowly accelerating to +speed.

http://cubic-bezier.com/#.42,0,1,1

static quad(t) #

A quadratic function, f(t) = t * t. Position equals the square of elapsed +time.

http://easings.net/#easeInQuad

static cubic(t) #

A cubic function, f(t) = t * t * t. Position equals the cube of elapsed +time.

http://easings.net/#easeInCubic

static poly(n) #

A power function. Position is equal to the Nth power of elapsed time.

n = 4: http://easings.net/#easeInQuart +n = 5: http://easings.net/#easeInQuint

static sin(t) #

A sinusoidal function.

http://easings.net/#easeInSine

static circle(t) #

A circular function.

http://easings.net/#easeInCirc

static exp(t) #

An exponential function.

http://easings.net/#easeInExpo

static elastic(bounciness) #

A simple elastic interaction, similar to a spring oscillating back and +forth.

Default bounciness is 1, which overshoots a little bit once. 0 bounciness +doesn't overshoot at all, and bounciness of N > 1 will overshoot about N +times.

http://easings.net/#easeInElastic

Wolfram Plots:

static back(s) #

Use with Animated.parallel() to create a simple effect where the object +animates back slightly as the animation starts.

Wolfram Plot:

static bounce(t) #

Provides a simple bouncing effect.

http://easings.net/#easeInBounce

static bezier(x1, y1, x2, y2) #

Provides a cubic bezier curve, equivalent to CSS Transitions' +transition-timing-function.

A useful tool to visualize cubic bezier curves can be found at +http://cubic-bezier.com/

static in(easing) #

Runs an easing function forwards.

static out(easing) #

Runs an easing function backwards.

static inOut(easing) #

Makes any easing function symmetrical. The easing function will run +forwards for half of the duration, then backwards for the rest of the +duration.

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

\ No newline at end of file diff --git a/releases/0.47/docs/flatlist.html b/releases/0.47/docs/flatlist.html new file mode 100644 index 00000000000..01f1e2cee96 --- /dev/null +++ b/releases/0.47/docs/flatlist.html @@ -0,0 +1,152 @@ +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 +prevent wasteful re-renders unless the actual id, selected, or title props change, even +if the inner SomeOtherWidget has no such optimizations.
  • By passing extraData={this.state} to FlatList we make sure FlatList itself will re-render +when the state.selected changes. Without setting this prop, FlatList would not know it +needs to re-render any items because it is also a PureComponent and the prop comparison will +not show any changes.
  • keyExtractor tells the list to use the ids for the react keys.
class MyListItem extends React.PureComponent { + _onPress = () => { + this.props.onPressItem(this.props.id); + }; + + render() { + return ( + <SomeOtherWidget + {...this.props} + onPress={this._onPress} + /> + ) + } +} + +class MyList extends React.PureComponent { + state = {selected: (new Map(): Map<string, boolean>)}; + + _keyExtractor = (item, index) => item.id; + + _onPressItem = (id: string) => { + // updater functions are preferred for transactional updates + this.setState((state) => { + // copy the map rather than modifying state. + const selected = new Map(state.selected); + selected.set(id, !selected.get(id)); // toggle + return {selected}; + }); + }; + + _renderItem = ({item}) => ( + <MyListItem + id={item.id} + onPressItem={this._onPressItem} + selected={!!this.state.selected.get(item.id)} + title={item.title} + /> + ); + + render() { + return ( + <FlatList + data={this.props.data} + extraData={this.state} + keyExtractor={this._keyExtractor} + renderItem={this._renderItem} + /> + ); + } +}

This is a convenience wrapper around <VirtualizedList>, +and thus inherits its 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 +(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. 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.

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) => ( + {length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index} +)}

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.

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.

inverted?: ?boolean #

Reverses the direction of scroll. Uses scale transforms of -1.

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 +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 +within half the visible length of the list.

onRefresh?: ?() => void #

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 #

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.

androidprogressViewOffset?: number #

Set this when offset is needed for the loading indicator to show correctly.

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. 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 in the list.

Check out scrollToOffset of VirtualizedList

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.

flashScrollIndicators() #

Displays the scroll indicators momentarily.

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

\ No newline at end of file diff --git a/releases/0.47/docs/flexbox.html b/releases/0.47/docs/flexbox.html new file mode 100644 index 00000000000..8af95625308 --- /dev/null +++ b/releases/0.47/docs/flexbox.html @@ -0,0 +1,82 @@ +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'; + +export default class FlexDirectionBasics extends Component { + render() { + return ( + // Try setting `flexDirection` to `column`. + <View style={{flex: 1, flexDirection: 'row'}}> + <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> + </View> + ); + } +}; + +// 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'; + +export default class JustifyContentBasics extends Component { + render() { + return ( + // Try setting `justifyContent` to `center`. + // Try setting `flexDirection` to `row`. + <View style={{ + flex: 1, + flexDirection: 'column', + justifyContent: 'space-between', + }}> + <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> + </View> + ); + } +}; + +// 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'; + +export default class AlignItemsBasics extends Component { + render() { + return ( + // Try setting `alignItems` to 'flex-start' + // Try setting `justifyContent` to `flex-end`. + // Try setting `flexDirection` to `row`. + <View style={{ + flex: 1, + flexDirection: 'column', + justifyContent: 'center', + alignItems: 'center', + }}> + <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} /> + <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> + </View> + ); + } +}; + +// skip this line if using Create React Native App +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 diff --git a/releases/0.47/docs/geolocation.html b/releases/0.47/docs/geolocation.html new file mode 100644 index 00000000000..cb7ed24cbd6 --- /dev/null +++ b/releases/0.47/docs/geolocation.html @@ -0,0 +1,45 @@ +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.

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 +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 requestAuthorization() #

Request suitable Location permission based on the key configured on pList. +If NSLocationAlwaysUsageDescription is set, it will request Always authorization, +although if NSLocationWhenInUseUsageDescription is set, it will request InUse +authorization.

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!

\ No newline at end of file diff --git a/releases/0.47/docs/gesture-responder-system.html b/releases/0.47/docs/gesture-responder-system.html new file mode 100644 index 00000000000..9bb6bee8c2b --- /dev/null +++ b/releases/0.47/docs/gesture-responder-system.html @@ -0,0 +1,19 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/getting-started.html b/releases/0.47/docs/getting-started.html new file mode 100644 index 00000000000..68acaf34a0d --- /dev/null +++ b/releases/0.47/docs/getting-started.html @@ -0,0 +1,271 @@ +Getting Started

Getting Started #

+ +

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.

+
    + + +
+
+ +
+ +

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 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.

+ +

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.

+ +

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 +
+ +
+ +

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.

+ +

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.

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 command:

choco install -y nodejs.install python2 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 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.

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

+ +

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 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. 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:

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

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".

+ +

Android Studio Welcome

+ +

Android Studio Welcome

+ +

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
+ +

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.

+ +

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).

+ +

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).

+ +

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".

+ +

Android Studio AVD Manager

+ +

Android Studio AVD Manager

+ +

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.

+ +

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.

+ +
+ +

That's it! #

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

+ +
+ +

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.

+ +

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.

+

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

\ No newline at end of file diff --git a/releases/0.47/docs/handling-text-input.html b/releases/0.47/docs/handling-text-input.html new file mode 100644 index 00000000000..f20ecfa3f24 --- /dev/null +++ b/releases/0.47/docs/handling-text-input.html @@ -0,0 +1,47 @@ +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'; + +export default class PizzaTranslator extends Component { + constructor(props) { + super(props); + this.state = {text: ''}; + } + + render() { + return ( + <View style={{padding: 10}}> + <TextInput + style={{height: 40}} + placeholder="Type here to translate!" + onChangeText={(text) => this.setState({text})} + /> + <Text style={{padding: 10, fontSize: 42}}> + {this.state.text.split(' ').map((word) => word && '🍕').join(' ')} + </Text> + </View> + ); + } +} + +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => 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 diff --git a/releases/0.47/docs/handling-touches.html b/releases/0.47/docs/handling-touches.html new file mode 100644 index 00000000000..ef5c2ecbfec --- /dev/null +++ b/releases/0.47/docs/handling-touches.html @@ -0,0 +1,146 @@ +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 all sorts of common gestures, as well as a comprehensive gesture responder system to allow for more advanced gesture recognition, but the one component you will most likely be interested in is the basic Button.

Displaying a basic button #

Button provides a basic button component that is rendered nicely on all platforms. The minimal example to display a button looks like this:

<Button + onPress={() => { Alert.alert('You tapped the button!')}} + title="Press Me" +/>

This will render a blue label on iOS, and a blue rounded rectangle with white text on Android. Pressing the button will call the "onPress" function, which in this case displays an alert popup. If you like, you can specify a "color" prop to change the color of your button.

Go ahead and play around with the Button component using the example below. You can select which platform your app is previewed in by clicking on the toggle in the bottom right, then click on "Tap to Play" to preview the app.

Touchables #

If the basic button doesn't look right for your app, you can build your own button using any of the "Touchable" components provided by React Native. The "Touchable" components provide the capability to capture tapping gestures, and can display feedback when a gesture is recognized. These components do not provide any default styling, however, so you will need to do a bit of work to get them looking nicely in your app.

Which "Touchable" 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.

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.

Let's see all of these in action:

Scrolling lists, swiping pages, and pinch-to-zoom #

Another gesture commonly used in mobile apps is the swipe or pan. This gesture allows the user to scroll through a list of items, or swipe through pages of content. In order to handle these and other gestures, we'll learn how to use a ScrollView next.

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

\ No newline at end of file diff --git a/releases/0.47/docs/headless-js-android.html b/releases/0.47/docs/headless-js-android.html new file mode 100644 index 00000000000..924ff23ec7d --- /dev/null +++ b/releases/0.47/docs/headless-js-android.html @@ -0,0 +1,34 @@ +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 { + + @Override + protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) { + Bundle extras = intent.getExtras(); + if (extras != null) { + return new HeadlessJsTaskConfig( + "SomeTaskName", + Arguments.fromBundle(extras), + 5000); + } + return null; + } +}

Now, whenever you start your service, e.g. as a periodic task or in response to some system event / broadcast, JS will spin up, run your task, then spin down.

Caveats #

  • By default, your app will crash if you try to run a task while the app is in the foreground. This is to prevent developers from shooting themselves in the foot by doing a lot of work in a task and slowing the UI. There is a way around this.
  • If you start your service from a BroadcastReceiver, make sure to call HeadlessJsTaskService.acquireWakelockNow() before returning from onReceive().

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

\ No newline at end of file diff --git a/releases/0.47/docs/height-and-width.html b/releases/0.47/docs/height-and-width.html new file mode 100644 index 00000000000..9d0d4aafc9d --- /dev/null +++ b/releases/0.47/docs/height-and-width.html @@ -0,0 +1,54 @@ +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'; + +export default class FixedDimensionsBasics extends Component { + render() { + return ( + <View> + <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> + <View style={{width: 100, height: 100, backgroundColor: 'skyblue'}} /> + <View style={{width: 150, height: 150, backgroundColor: 'steelblue'}} /> + </View> + ); + } +} + +// 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'; + +export default class FlexDimensionsBasics extends Component { + render() { + return ( + // Try removing the `flex: 1` on the parent View. + // The parent will not have dimensions, so the children can't expand. + // What if you add `height: 300` instead of `flex: 1`? + <View style={{flex: 1}}> + <View style={{flex: 1, backgroundColor: 'powderblue'}} /> + <View style={{flex: 2, backgroundColor: 'skyblue'}} /> + <View style={{flex: 3, backgroundColor: 'steelblue'}} /> + </View> + ); + } +} + +// skip this line if using Create React Native App +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 diff --git a/releases/0.47/docs/image.html b/releases/0.47/docs/image.html new file mode 100644 index 00000000000..a26ed5d199a --- /dev/null +++ b/releases/0.47/docs/image.html @@ -0,0 +1,143 @@ +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'; + +export default class DisplayAnImage extends Component { + render() { + return ( + <View> + <Image + source={require('./img/favicon.png')} + /> + <Image + style={{width: 50, height: 50}} + source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} + /> + </View> + ); + } +} + +// 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({ + stretch: { + width: 50, + height: 200 + } +}); + +export default class DisplayAnImageWithStyle extends Component { + render() { + return ( + <View> + <Image + style={styles.stretch} + source={require('./img/favicon.png')} + /> + </View> + ); + } +} + +// skip these lines if using Create React Native App +AppRegistry.registerComponent( + 'DisplayAnImageWithStyle', + () => DisplayAnImageWithStyle +);

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:1.0.1' + + // For animated GIF support + compile 'com.facebook.fresco:animated-gif:1.0.1' + + // For WebP support, including animated WebP + 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: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 #

blurRadius?: PropTypes.number #

blurRadius: the blur radius of the blur filter added to the image

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) +so that both dimensions (width and height) of the image will be equal to +or less than the corresponding dimension of the view (minus padding).

  • stretch: Scale width and height independently, This may change the +aspect ratio of the src.

  • repeat: Repeat the image to cover the frame of the view. The +image will keep it's size and aspect ratio. (iOS only)

source?: ImageSourcePropType #

The image source (either a remote URL or a local file resource).

This prop can also contain several remote URLs, specified together with +their width and height and potentially with scale/other URI arguments. +The native side will then choose the best uri to display based on the +measured size of the image container. A cache property can be added to +control how networked request interacts with the local cache.

The currently supported formats are png, jpg, jpeg, bmp, gif, +webp (Android only), psd (iOS only).

style?: style #

backfaceVisibility ReactPropTypes.oneOf(['visible', 'hidden'])
backgroundColor color
borderBottomLeftRadius ReactPropTypes.number
borderBottomRightRadius ReactPropTypes.number
borderColor color
borderRadius ReactPropTypes.number
borderTopLeftRadius ReactPropTypes.number
borderTopRightRadius ReactPropTypes.number
borderWidth ReactPropTypes.number
opacity ReactPropTypes.number
overflow ReactPropTypes.oneOf(['visible', 'hidden'])
resizeMode ReactPropTypes.oneOf(Object.keys(ImageResizeMode))
tintColor color

Changes the color of all the non-transparent pixels to the tintColor.

androidoverlayColor ReactPropTypes.string

When the image has rounded corners, specifying an overlayColor will +cause the remaining space in the corners to be filled with a solid color. +This is useful in cases which are not supported by the Android +implementation of rounded corners: + - Certain resize modes, such as 'contain' + - Animated GIFs

A typical way to use this prop is with images displayed on a solid +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?: 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?: 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.

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?: 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?: 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?: 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 +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!

\ No newline at end of file diff --git a/releases/0.47/docs/imageeditor.html b/releases/0.47/docs/imageeditor.html new file mode 100644 index 00000000000..7ef71ff0e05 --- /dev/null +++ b/releases/0.47/docs/imageeditor.html @@ -0,0 +1,24 @@ +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 +callback will point to the image in the store. Remember to delete the +cropped image from the ImageStore when you are done with it.

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

\ No newline at end of file diff --git a/releases/0.47/docs/imagepickerios.html b/releases/0.47/docs/imagepickerios.html new file mode 100644 index 00000000000..6c44f52dc26 --- /dev/null +++ b/releases/0.47/docs/imagepickerios.html @@ -0,0 +1,19 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/images.html b/releases/0.47/docs/images.html new file mode 100644 index 00000000000..2a5788d6ccf --- /dev/null +++ b/releases/0.47/docs/images.html @@ -0,0 +1,57 @@ +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 + └── check@3x.png

...and button.js code contains:

<Image source={require('./img/check.png')} />

...the packager will bundle and serve the image corresponding to device's screen density. For example, check@2x.png, will be used on an iPhone 7, whilecheck@3x.png will be used on an iPhone 7 Plus or a Nexus 5. If there is no image matching the screen density, the closest best option will be selected.

On Windows, you might need to restart the packager if you add new images to your project.

Here are some benefits that you get:

  1. Same system on iOS and Android.
  2. Images live in the same folder as your JavaScript code. Components are self-contained.
  3. No global namespace, i.e. you don't have to worry about name collisions.
  4. Only the images that are actually used will be packaged into your app.
  5. Adding and changing images doesn't require app recompilation, just refresh the simulator as you normally do.
  6. The packager knows the image dimensions, no need to duplicate it in the code.
  7. Images can be distributed via npm packages.

In order for this to work, the image name in require has to be known statically.

// GOOD +<Image source={require('./my-icon.png')} /> + +// BAD +var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive'; +<Image source={require('./' + icon + '.png')} /> + +// GOOD +var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png'); +<Image source={icon} />

Note that image sources required this way include size (width, height) info for the Image. If you need to scale the image dynamically (i.e. via flex), you may need to manually set { width: undefined, height: undefined } on the style attribute.

Static Non-Image Resources #

The require syntax described above can be used to statically include audio, video or document files in your project as well. Most common file types are supported including .mp3, .wav, .mp4, .mov, .html and .pdf. See packager defaults for the full list.

You can add support for other types by creating a packager config file (see the packager config file for the full list of configuration options).

A caveat is that videos must use absolute positioning instead of flexGrow, since size info is not currently passed for non-image assets. This limitation doesn't occur for videos that are linked directly into Xcode or the Assets folder for Android.

Images From Hybrid App's Resources #

If you are building a hybrid app (some UIs in React Native, some UIs in platform code) you can still use images that are already bundled into the app.

For images included via Xcode asset catalogs or in the Android drawable folder, use the image name without the extension:

<Image source={{uri: 'app_icon'}} style={{width: 40, height: 40}} />

For images in the Android assets folder, use the asset:/ scheme:

<Image source={{uri: 'asset:/app_icon.png'}} style={{width: 40, height: 40}} />

These approaches provide no safety checks. It's up to you to guarantee that those images are available in the application. Also you have to specify image dimensions manually.

Network Images #

Many of the images you will display in your app will not be available at compile time, or you will want to load some dynamically to keep the binary size down. Unlike with static resources, you will need to manually specify the dimensions of your image. It's highly recommended that you use https as well in order to satisfy App Transport Security requirements on iOS.

// GOOD +<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} + style={{width: 400, height: 400}} /> + +// BAD +<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.

  • default: Use the native platforms default strategy.
  • reload: The data for the URL will be loaded from the originating source. +No existing cache data should be used to satisfy a URL load request.
  • force-cache: The existing cached data will be used to satisfy the request, +regardless of its age or expiration date. If there is no existing data in the cache +corresponding the request, the data is loaded from the originating source.
  • only-if-cached: The existing cache data will be used to satisfy a request, regardless of +its age or expiration date. If there is no existing data in the cache corresponding +to a URL load request, no attempt is made to load the data from the originating source, +and the load is considered to have failed.
<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png', cache: 'only-if-cached'}} + style={{width: 400, height: 400}} />

Local Filesystem Images #

See CameraRoll for an example of +using local resources that are outside of Images.xcassets.

Best Camera Roll Image #

iOS saves multiple sizes for the same image in your Camera Roll, it is very important to pick the one that's as close as possible for performance reasons. You wouldn't want to use the full quality 3264x2448 image as source when displaying a 200x200 thumbnail. If there's an exact match, React Native will pick it, otherwise it's going to use the first one that's at least 50% bigger in order to avoid blur when resizing from a close size. All of this is done by default so you don't have to worry about writing the tedious (and error prone) code to do it yourself.

Why Not Automatically Size Everything? #

In the browser if you don't give a size to an image, the browser is going to render a 0x0 element, download the image, and then render the image based with the correct size. The big issue with this behavior is that your UI is going to jump all around as images load, this makes for a very bad user experience.

In React Native this behavior is intentionally not implemented. It is more work for the developer to know the dimensions (or aspect ratio) of the remote image in advance, but we believe that it leads to a better user experience. Static images loaded from the app bundle via the require('./my-icon.png') syntax can be automatically sized because their dimensions are available immediately at the time of mounting.

For example, the result of require('./my-icon.png') might be:

{"__packager_asset":true,"uri":"my-icon.png","width":591,"height":573}

Source as an object #

In React Native, one interesting decision is that the src attribute is named source and doesn't take a string but an object with a uri attribute.

<Image source={{uri: 'something.jpg'}} />

On the infrastructure side, the reason is that it allows us to attach metadata to this object. For example if you are using require('./my-icon.png'), then we add information about its actual location and size (don't rely on this fact, it might change in the future!). This is also future proofing, for example we may want to support sprites at some point, instead of outputting {uri: ...}, we can output {uri: ..., crop: {left: 10, top: 50, width: 20, height: 40}} and transparently support spriting on all the existing call sites.

On the user side, this lets you annotate the object with useful attributes such as the dimension of the image in order to compute the size it's going to be displayed in. Feel free to use it as your data structure to store more information about your image.

Background Image via Nesting #

A common feature request from developers familiar with the web is background-image. To handle this use case, simply create a normal <Image> component and add whatever children to it you would like to layer on top of it.

return ( + <Image source={...}> + <Text>Inside</Text> + </Image> +);

iOS Border Radius Styles #

Please note that the following corner specific, border radius style properties are currently ignored by iOS's image component:

  • borderTopLeftRadius
  • borderTopRightRadius
  • borderBottomLeftRadius
  • borderBottomRightRadius

Off-thread Decoding #

Image decoding can take more than a frame-worth of time. This is one of the major sources of frame drops on the web because decoding is done in the main thread. In React Native, image decoding is done in a different thread. In practice, you already need to handle the case when the image is not downloaded yet, so displaying the placeholder for a few more frames while it is decoding does not require any code change.

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

\ No newline at end of file diff --git a/releases/0.47/docs/imagestore.html b/releases/0.47/docs/imagestore.html new file mode 100644 index 00000000000..582a13b44da --- /dev/null +++ b/releases/0.47/docs/imagestore.html @@ -0,0 +1,37 @@ +ImageStore

ImageStore #

Methods #

static hasImageForTag(uri, callback) #

Check if the ImageStore contains image data for the specified URI. +@platform ios

static removeImageForTag(uri) #

Delete an image from the ImageStore. Images are stored in memory and +must be manually removed when you are finished with them, otherwise they +will continue to use up RAM until the app is terminated. It is safe to +call removeImageForTag() without first calling hasImageForTag(), it +will simply fail silently. +@platform ios

static addImageFromBase64(base64ImageData, success, failure) #

Stores a base64-encoded image in the ImageStore, and returns a URI that +can be used to access or display the image later. Images are stored in +memory only, and must be manually deleted when you are finished with +them by calling removeImageForTag().

Note that it is very inefficient to transfer large quantities of binary +data between JS and native code, so you should avoid calling this more +than necessary. +@platform ios

static getBase64ForTag(uri, success, failure) #

Retrieves the base64-encoded data for an image in the ImageStore. If the +specified URI does not match an image in the store, the failure callback +will be called.

Note that it is very inefficient to transfer large quantities of binary +data between JS and native code, so you should avoid calling this more +than necessary. To display an image in the ImageStore, you can just pass +the URI to an <Image/> component; there is no need to retrieve the +base64 data.

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

\ No newline at end of file diff --git a/releases/0.47/docs/imagestyleproptypes.html b/releases/0.47/docs/imagestyleproptypes.html new file mode 100644 index 00000000000..e0d179fa049 --- /dev/null +++ b/releases/0.47/docs/imagestyleproptypes.html @@ -0,0 +1,27 @@ +ImageStylePropTypes

ImageStylePropTypes #

Props #

backfaceVisibility?: ReactPropTypes.oneOf(['visible', 'hidden']) #

backgroundColor?: color #

borderBottomLeftRadius?: ReactPropTypes.number #

borderBottomRightRadius?: ReactPropTypes.number #

borderColor?: color #

borderRadius?: ReactPropTypes.number #

borderTopLeftRadius?: ReactPropTypes.number #

borderTopRightRadius?: ReactPropTypes.number #

borderWidth?: ReactPropTypes.number #

opacity?: ReactPropTypes.number #

overflow?: ReactPropTypes.oneOf(['visible', 'hidden']) #

resizeMode?: ReactPropTypes.oneOf(Object.keys(ImageResizeMode)) #

tintColor?: color #

Changes the color of all the non-transparent pixels to the tintColor.

androidoverlayColor?: ReactPropTypes.string #

When the image has rounded corners, specifying an overlayColor will +cause the remaining space in the corners to be filled with a solid color. +This is useful in cases which are not supported by the Android +implementation of rounded corners: + - Certain resize modes, such as 'contain' + - Animated GIFs

A typical way to use this prop is with images displayed on a solid +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

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

\ No newline at end of file diff --git a/releases/0.47/docs/integration-with-existing-apps.html b/releases/0.47/docs/integration-with-existing-apps.html new file mode 100644 index 00000000000..142c6ccb9b3 --- /dev/null +++ b/releases/0.47/docs/integration-with-existing-apps.html @@ -0,0 +1,438 @@ +Integration With Existing Apps

Integration With Existing Apps #

+ +

React Native is great when you are starting a new mobile app from scratch. However, it also works well for adding a single view or user flow to existing native applications. With a few steps, you can add new React Native based features, screens, views, etc.

The specific steps are different depending on what platform you're targeting.

+
    + + + +
+
+ +
+ +

Key Concepts #

+ +

The keys to integrating React Native components into your iOS application are to:

  1. Set up React Native dependencies and directory structure.
  2. Understand what React Native components you will use in your app.
  3. Add these components as dependencies using CocoaPods.
  4. Develop your React Native components in JavaScript.
  5. Add a RCTRootView to your iOS app. This view will serve as the container for your React Native component.
  6. Start the React Native server and run your native application.
  7. Verify that the React Native aspect of your application works as expected.
+ +

The keys to integrating React Native components into your Android application are to:

  1. Set up React Native dependencies and directory structure.
  2. Develop your React Native components in JavaScript.
  3. Add a ReactRootView to your Android app. This view will serve as the container for your React Native component.
  4. Start the React Native server and run your native application.
  5. Verify that the React Native aspect of your application works as expected.
+ +

Prerequisites #

+ +

Follow the instructions for building apps with native code from the Getting Started guide to configure your development environment for building React Native apps for iOS.

1. Set up directory structure #

To ensure a smooth experience, create a new folder for your integrated React Native project, then copy your existing iOS project to a /ios subfolder.

+ +

Follow the instructions for building apps with native code from the Getting Started guide to configure your development environment for building React Native apps for Android.

1. Set up directory structure #

To ensure a smooth experience, create a new folder for your integrated React Native project, then copy your existing Android project to a /android subfolder.

+ +

2. Install JavaScript dependencies #

Go to the root directory for your project and create a new package.json file with the following contents:

{ + "name": "MyReactNativeApp", + "version": "0.0.1", + "private": true, + "scripts": { + "start": "node node_modules/react-native/local-cli/cli.js start" + } +}

Next, you will install the react and react-native packages. Open a terminal or command prompt, then navigate to the root directory for your project and type the following commands:

$ npm install --save react react-native

This will create a new /node_modules folder in your project's root directory. This folder stores all the JavaScript dependencies required to build your project.

+ +

3. Install CocoaPods #

CocoaPods is a package management tool for iOS and macOS development. We use it to add the actual React Native framework code locally into your current project.

We recommend installing CocoaPods using Homebrew.

$ brew install cocoapods

It is technically possible not to use CocoaPods, but that would require manual library and linker additions that would overly complicate this process.

+ +

Adding React Native to your app #

+ +

Assume the app for integration is a 2048 game. Here is what the main menu of the native application looks like without React Native.

+ +

Assume the app for integration is a 2048 game. Here is what the main menu of the native application looks like without React Native.

+ +

Before RN Integration

Configuring CocoaPods dependencies #

Before you integrate React Native into your application, you will want to decide what parts of the React Native framework you would like to integrate. We will use CocoaPods to specify which of these "subspecs" your app will depend on.

The list of supported subspecs is available in /node_modules/react-native/React.podspec. They are generally named by functionality. For example, you will generally always want the Core subspec. That will get you the AppRegistry, StyleSheet, View and other core React Native libraries. If you want to add the React Native Text library (e.g., for <Text> elements), then you will need the RCTText subspec. If you want the Image library (e.g., for <Image> elements), then you will need the RCTImage subspec.

You can specify which subspecs your app will depend on in a Podfile file. The easiest way to create a Podfile is by running the CocoaPods init command in the /ios subfolder of your project:

$ pod init

The Podfile will contain a boilerplate setup that you will tweak for your integration purposes. In the end, Podfile should look something similar to this:

+ +
# The target name is most likely the name of your project. +target 'NumberTileGame' do + + # Your 'node_modules' directory is probably in the root of your project, + # but if not, adjust the `:path` accordingly + pod 'React', :path => '../node_modules/react-native', :subspecs => [ + 'Core', + 'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43 + 'RCTText', + 'RCTNetwork', + 'RCTWebSocket', # needed for debugging + # Add any other subspecs you want to use in your project + ] + # Explicitly include Yoga if you are using RN >= 0.42.0 + pod "Yoga", :path => "../node_modules/react-native/ReactCommon/yoga" + +end
+ +
source 'https://github.com/CocoaPods/Specs.git' + +# Required for Swift apps +platform :ios, '8.0' +use_frameworks! + +# The target name is most likely the name of your project. +target 'swift-2048' do + + # Your 'node_modules' directory is probably in the root of your project, + # but if not, adjust the `:path` accordingly + pod 'React', :path => '../node_modules/react-native', :subspecs => [ + 'Core', + 'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43 + 'RCTText', + 'RCTNetwork', + 'RCTWebSocket', # needed for debugging + # Add any other subspecs you want to use in your project + ] + # Explicitly include Yoga if you are using RN >= 0.42.0 + pod "Yoga", :path => "../node_modules/react-native/ReactCommon/yoga" + +end
+ +

After you have created your Podfile, you are ready to install the React Native pod.

$ pod install

You should see output such as:

Analyzing dependencies +Fetching podspec for `React` from `../node_modules/react-native` +Downloading dependencies +Installing React (0.26.0) +Generating Pods project +Integrating client project +Sending stats +Pod installation complete! There are 3 dependencies from the Podfile and 1 total pod installed.
+ +

If you get a warning such as "The swift-2048 [Debug] target overrides the FRAMEWORK_SEARCH_PATHS build setting defined in Pods/Target Support Files/Pods-swift-2048/Pods-swift-2048.debug.xcconfig. This can lead to problems with the CocoaPods installation", then make sure the Framework Search Paths in Build Settings for both Debug and Release only contain $(inherited).

+ +

Code integration #

Now we will actually modify the native iOS application to integrate React Native. For our 2048 sample app, we will add a "High Score" screen in React Native.

The React Native component #

The first bit of code we will write is the actual React Native code for the new "High Score" screen that will be integrated into our application.

1. Create a index.ios.js file #

First, create an empty index.ios.js file in the root of your React Native project.

index.ios.js is the starting point for React Native applications on iOS, and it is always required. It can be a small file that requires other file that are part of your React Native component or application, or it can contain all the code that is needed for it. In our case, we will just put everything in index.ios.js.

2. Add your React Native code #

In your index.ios.js, create your component. In our sample here, we will add simple <Text> component within a styled <View>

'use strict'; + +import React from 'react'; +import { + AppRegistry, + StyleSheet, + Text, + View +} from 'react-native'; + +class RNHighScores extends React.Component { + render() { + var contents = this.props["scores"].map( + score => <Text key={score.name}>{score.name}:{score.value}{"\n"}</Text> + ); + return ( + <View style={styles.container}> + <Text style={styles.highScoresTitle}> + 2048 High Scores! + </Text> + <Text style={styles.scores}> + {contents} + </Text> + </View> + ); + } +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: 'center', + alignItems: 'center', + backgroundColor: '#FFFFFF', + }, + highScoresTitle: { + fontSize: 20, + textAlign: 'center', + margin: 10, + }, + scores: { + textAlign: 'center', + color: '#333333', + marginBottom: 5, + }, +}); + +// Module name +AppRegistry.registerComponent('AwesomeProject', () => RNHighScores);

RNHighScores is the name of your module that will be used when you add a view to React Native from within your iOS application.

The Magic: RCTRootView #

Now that your React Native component is created via index.ios.js, you need to add that component to a new or existing ViewController. The easiest path to take is to optionally create an event path to your component and then add that component to an existing ViewController.

We will tie our React Native component with a new native view in the ViewController that will actually host it called RCTRootView .

1. Create an Event Path #

You can add a new link on the main game menu to go to the "High Score" React Native page.

Event Path

2. Event Handler #

We will now add an event handler from the menu link. A method will be added to the main ViewController of your application. This is where RCTRootView comes into play.

When you build a React Native application, you use the React Native packager to create an index.ios.bundle that will be served by the React Native server. Inside index.ios.bundle will be our RNHighScore module. So, we need to point our RCTRootView to the location of the index.ios.bundle resource (via NSURL) and tie it to the module.

We will, for debugging purposes, log that the event handler was invoked. Then, we will create a string with the location of our React Native code that exists inside the index.ios.bundle. Finally, we will create the main RCTRootView. Notice how we provide RNHighScores as the moduleName that we created above when writing the code for our React Native component.

+ +

First import the RCTRootView header.

#import <React/RCTRootView.h>

The initialProperties are here for illustration purposes so we have some data for our high score screen. In our React Native component, we will use this.props to get access to that data.

- (IBAction)highScoreButtonPressed:(id)sender { + NSLog(@"High Score Button Pressed"); + NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"]; + + RCTRootView *rootView = + [[RCTRootView alloc] initWithBundleURL: jsCodeLocation + moduleName: @"RNHighScores" + initialProperties: + @{ + @"scores" : @[ + @{ + @"name" : @"Alex", + @"value": @"42" + }, + @{ + @"name" : @"Joel", + @"value": @"10" + } + ] + } + launchOptions: nil]; + UIViewController *vc = [[UIViewController alloc] init]; + vc.view = rootView; + [self presentViewController:vc animated:YES completion:nil]; +}

Note that RCTRootView initWithURL starts up a new JSC VM. To save resources and simplify the communication between RN views in different parts of your native app, you can have multiple views powered by React Native that are associated with a single JS runtime. To do that, instead of using [RCTRootView alloc] initWithURL, use RCTBridge initWithBundleURL to create a bridge and then use RCTRootView initWithBridge.

+ +

First import the React library.

import React

The initialProperties are here for illustration purposes so we have some data for our high score screen. In our React Native component, we will use this.props to get access to that data.

@IBAction func highScoreButtonTapped(sender : UIButton) { + NSLog("Hello") + let jsCodeLocation = URL(string: "http://localhost:8081/index.ios.bundle?platform=ios") + let mockData:NSDictionary = ["scores": + [ + ["name":"Alex", "value":"42"], + ["name":"Joel", "value":"10"] + ] + ] + + let rootView = RCTRootView( + bundleURL: jsCodeLocation, + moduleName: "RNHighScores", + initialProperties: mockData as [NSObject : AnyObject], + launchOptions: nil + ) + let vc = UIViewController() + vc.view = rootView + self.present(vc, animated: true, completion: nil) +}

Note that RCTRootView bundleURL starts up a new JSC VM. To save resources and simplify the communication between RN views in different parts of your native app, you can have multiple views powered by React Native that are associated with a single JS runtime. To do that, instead of using RCTRootView bundleURL, use RCTBridge initWithBundleURL to create a bridge and then use RCTRootView initWithBridge.

+ +

When moving your app to production, the NSURL can point to a pre-bundled file on disk via something like [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];. You can use the react-native-xcode.sh script in node_modules/react-native/scripts/ to generate that pre-bundled file.

+ +

When moving your app to production, the NSURL can point to a pre-bundled file on disk via something like let mainBundle = NSBundle(URLForResource: "main" withExtension:"jsbundle"). You can use the react-native-xcode.sh script in node_modules/react-native/scripts/ to generate that pre-bundled file.

+ +
3. Wire Up #

Wire up the new link in the main menu to the newly added event handler method.

Event Path

One of the easier ways to do this is to open the view in the storyboard and right click on the new link. Select something such as the Touch Up Inside event, drag that to the storyboard and then select the created method from the list provided.

Test your integration #

You have now done all the basic steps to integrate React Native with your current application. Now we will start the React Native packager to build the index.ios.bundle package and the server running on localhost to serve it.

1. Add App Transport Security exception #

Apple has blocked implicit cleartext HTTP resource loading. So we need to add the following our project's Info.plist (or equivalent) file.

<key>NSAppTransportSecurity</key> +<dict> + <key>NSExceptionDomains</key> + <dict> + <key>localhost</key> + <dict> + <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> + <true/> + </dict> + </dict> +</dict>

App Transport Security is good for your users. Make sure to re-enable it prior to releasing your app for production.

2. Run the packager #

To run your app, you need to first start the development server. To do this, simply run the following command in the root directory of your React Native project:

$ npm start
3. Run the app #

If you are using Xcode or your favorite editor, build and run your native iOS application as normal. Alternatively, you can run the app from the command line using:

# From the root of your project +$ react-native run-ios

In our sample application, you should see the link to the "High Scores" and then when you click on that you will see the rendering of your React Native component.

Here is the native application home screen:

Home Screen

Here is the React Native high score screen:

High Scores

If you are getting module resolution issues when running your application please see this GitHub issue for information and possible resolution. This comment seemed to be the latest possible resolution.

See the Code #

+ +

You can examine the code that added the React Native screen to our sample app on GitHub.

+ +

You can examine the code that added the React Native screen to our sample app on GitHub.

+ +

Adding React Native to your app #

Configuring maven #

Add the React Native dependency to your app's build.gradle file:

dependencies { + ... + compile "com.facebook.react:react-native:+" // From node_modules. +}

If you want to ensure that you are always using a specific React Native version in your native build, replace + with an actual React Native version you've downloaded from npm.

Add an entry for the local React Native maven directory to build.gradle. Be sure to add it to the "allprojects" block:

allprojects { + repositories { + ... + maven { + // All of React Native (JS, Android binaries) is installed from npm + url "$rootDir/node_modules/react-native/android" + } + } + ... +}

Make sure that the path is correct! You shouldn’t run into any “Failed to resolve: com.facebook.react:react-native:0.x.x" errors after running Gradle sync in Android Studio.

Configuring permissions #

Next, make sure you have the Internet permission in your AndroidManifest.xml:

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

If you need to access to the DevSettingsActivity add to your AndroidManifest.xml:

<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

This is only really used in dev mode when reloading JavaScript from the development server, so you can strip this in release builds if you need to.

Code integration #

Now we will actually modify the native Android application to integrate React Native.

The React Native component #

The first bit of code we will write is the actual React Native code for the new "High Score" screen that will be integrated into our application.

1. Create a index.android.js file #

First, create an empty index.android.js file in the root of your React Native project.

index.android.js is the starting point for React Native applications on Android, and it is always required. It can be a small file that requires other file that are part of your React Native component or application, or it can contain all the code that is needed for it. In our case, we will just put everything in index.android.js.

2. Add your React Native code #

In your index.android.js, create your component. In our sample here, we will add simple <Text> component within a styled <View>:

'use strict'; + +import React from 'react'; +import { + AppRegistry, + StyleSheet, + Text, + View +} from 'react-native'; + +class HelloWorld extends React.Component { + render() { + return ( + <View style={styles.container}> + <Text style={styles.hello}>Hello, World</Text> + </View> + ) + } +} +var styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: 'center', + }, + hello: { + fontSize: 20, + textAlign: 'center', + margin: 10, + }, +}); + +AppRegistry.registerComponent('AwesomeProject', () => HelloWorld);
3. Configure permissions for development error overlay #

If your app is targeting the Android API level 23 or greater, make sure you have the overlay permission enabled for the development build. You can check it with Settings.canDrawOverlays(this);. This is required in dev builds because react native development errors must be displayed above all the other windows. Due to the new permissions system introduced in the API level 23, the user needs to approve it. This can be achieved by adding the following code to the Activity file in the onCreate() method. OVERLAY_PERMISSION_REQ_CODE is a field of the class which would be responsible for passing the result back to the Activity.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (!Settings.canDrawOverlays(this)) { + Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, + Uri.parse("package:" + getPackageName())); + startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE); + } +}

Finally, the onActivityResult() method (as shown in the code below) has to be overridden to handle the permission Accepted or Denied cases for consistent UX.

@Override +protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (requestCode == OVERLAY_PERMISSION_REQ_CODE) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (!Settings.canDrawOverlays(this)) { + // SYSTEM_ALERT_WINDOW permission not granted... + } + } + } +}

The Magic: ReactRootView #

You need to add some native code in order to start the React Native runtime and get it to render something. To do this, we're going to create an Activity that creates a ReactRootView, starts a React application inside it and sets it as the main content view.

If you are targetting Android version <5, use the AppCompatActivity class from the com.android.support:appcompat package instead of Activity.

public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler { + private ReactRootView mReactRootView; + private ReactInstanceManager mReactInstanceManager; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mReactRootView = new ReactRootView(this); + mReactInstanceManager = ReactInstanceManager.builder() + .setApplication(getApplication()) + .setBundleAssetName("index.android.bundle") + .setJSMainModuleName("index.android") + .addPackage(new MainReactPackage()) + .setUseDeveloperSupport(BuildConfig.DEBUG) + .setInitialLifecycleState(LifecycleState.RESUMED) + .build(); + mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null); + + setContentView(mReactRootView); + } + + @Override + public void invokeDefaultOnBackPressed() { + super.onBackPressed(); + } +}

If you are using a starter kit for React Native, replace the "HelloWorld" string with the one in your index.android.js file (it’s the first argument to the AppRegistry.registerComponent() method).

If you are using Android Studio, use Alt + Enter to add all missing imports in your MyReactActivity class. Be careful to use your package’s BuildConfig and not the one from the ...facebook... package.

We need set the theme of MyReactActivity to Theme.AppCompat.Light.NoActionBar because some components rely on this theme.

<activity + android:name=".MyReactActivity" + android:label="@string/app_name" + android:theme="@style/Theme.AppCompat.Light.NoActionBar"> +</activity>

A ReactInstanceManager can be shared amongst multiple activities and/or fragments. You will want to make your own ReactFragment or ReactActivity and have a singleton holder that holds a ReactInstanceManager. When you need the ReactInstanceManager (e.g., to hook up the ReactInstanceManager to the lifecycle of those Activities or Fragments) use the one provided by the singleton.

Next, we need to pass some activity lifecycle callbacks down to the ReactInstanceManager:

@Override +protected void onPause() { + super.onPause(); + + if (mReactInstanceManager != null) { + mReactInstanceManager.onHostPause(this); + } +} + +@Override +protected void onResume() { + super.onResume(); + + if (mReactInstanceManager != null) { + mReactInstanceManager.onHostResume(this, this); + } +} + +@Override +protected void onDestroy() { + super.onDestroy(); + + if (mReactInstanceManager != null) { + mReactInstanceManager.onHostDestroy(); + } +}

We also need to pass back button events to React Native:

@Override + public void onBackPressed() { + if (mReactInstanceManager != null) { + mReactInstanceManager.onBackPressed(); + } else { + super.onBackPressed(); + } +}

This allows JavaScript to control what happens when the user presses the hardware back button (e.g. to implement navigation). When JavaScript doesn't handle a back press, your invokeDefaultOnBackPressed method will be called. By default this simply finishes your Activity.

Finally, we need to hook up the dev menu. By default, this is activated by (rage) shaking the device, but this is not very useful in emulators. So we make it show when you press the hardware menu button (use Ctrl + M if you're using Android Studio emulator):

@Override +public boolean onKeyUp(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) { + mReactInstanceManager.showDevOptionsDialog(); + return true; + } + return super.onKeyUp(keyCode, event); +}

Now your activity is ready to run some JavaScript code.

Test your integration #

You have now done all the basic steps to integrate React Native with your current application. Now we will start the React Native packager to build the index.android.bundle package and the server running on localhost to serve it.

1. Run the packager #

To run your app, you need to first start the development server. To do this, simply run the following command in the root directory of your React Native project:

$ npm start
2. Run the app #

Now build and run your Android app as normal.

Once you reach your React-powered activity inside the app, it should load the JavaScript code from the development server and display:

Screenshot

Creating a release build in Android Studio #

You can use Android Studio to create your release builds too! It’s as easy as creating release builds of your previously-existing native Android app. There’s just one additional step, which you’ll have to do before every release build. You need to execute the following to create a React Native bundle, which will be included with your native Android app:

$ react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/com/your-company-name/app-package-name/src/main/assets/index.android.bundle --assets-dest android/com/your-company-name/app-package-name/src/main/res/

Don’t forget to replace the paths with correct ones and create the assets folder if it doesn’t exist.

Now just create a release build of your native app from within Android Studio as usual and you should be good to go!

+ +

Now what? #

At this point you can continue developing your app as usual. Refer to our debugging and deployment docs to learn more about working with React Native.

+

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

\ No newline at end of file diff --git a/releases/0.47/docs/interactionmanager.html b/releases/0.47/docs/interactionmanager.html new file mode 100644 index 00000000000..4d3228d575e --- /dev/null +++ b/releases/0.47/docs/interactionmanager.html @@ -0,0 +1,44 @@ +InteractionManager

InteractionManager #

InteractionManager allows long-running work to be scheduled after any +interactions/animations have completed. In particular, this allows JavaScript +animations to run smoothly.

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(): 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) +// later, on animation completion: +InteractionManager.clearInteractionHandle(handle); +// queued tasks run if all handles were cleared

runAfterInteractions takes either a plain callback function, or a +PromiseTask object with a gen method that returns a Promise. If a +PromiseTask is supplied, then it is fully resolved (including asynchronous +dependencies that also schedule more tasks via runAfterInteractions) before +starting on the next task that might have been queued up synchronously +earlier.

By default, queued tasks are executed together in a loop in one +setImmediate batch. If setDeadline is called with a positive number, then +tasks will only be executed until the deadline (in terms of js event loop run +time) approaches, at which point execution will yield via setTimeout, +allowing events such as touches to start interactions and block queued tasks +from executing, making apps more responsive.

Methods #

static runAfterInteractions(task) #

Schedule a function to run after all interactions have completed. Returns a cancellable +"promise".

static createInteractionHandle() #

Notify manager that an interaction has started.

static clearInteractionHandle(handle) #

Notify manager that an interaction has completed.

static setDeadline(deadline) #

A positive number will use setTimeout to schedule any tasks after the +eventLoopRunningTime hits the deadline value, otherwise all tasks will be +executed in one setImmediate batch (default).

Properties #

Events: CallExpression #

addListener: CallExpression #

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

\ No newline at end of file diff --git a/releases/0.47/docs/javascript-environment.html b/releases/0.47/docs/javascript-environment.html new file mode 100644 index 00000000000..d6806f3dc09 --- /dev/null +++ b/releases/0.47/docs/javascript-environment.html @@ -0,0 +1,19 @@ +JavaScript Environment

JavaScript Environment #

JavaScript Runtime #

When using React Native, you're going to be running your JavaScript code in two environments:

  • On iOS simulators and devices, Android emulators and devices React Native uses JavaScriptCore which is the JavaScript engine that powers Safari. On iOS JSC doesn't use JIT due to the absence of writable executable memory in iOS apps.
  • When using Chrome debugging, it runs all the JavaScript code within Chrome itself and communicates with native code via WebSocket. So you are using V8.

While both environments are very similar, you may end up hitting some inconsistencies. We're likely going to experiment with other JS engines in the future, so it's best to avoid relying on specifics of any runtime.

JavaScript Syntax Transformers #

Syntax transformers make writing code more enjoyable by allowing you to use new JavaScript syntax without having to wait for support on all interpreters.

As of version 0.5.0, React Native ships with the Babel JavaScript compiler. Check Babel documentation on its supported transformations for more details.

Here's a full list of React Native's enabled transformations.

ES5

  • Reserved Words: promise.catch(function() { });

ES6

ES7

Specific

  • JSX: <View style={{color: 'red'}} />
  • Flow: function foo(x: ?number): string {}

Polyfills #

Many standards functions are also available on all the supported JavaScript runtimes.

Browser

ES6

ES7

Specific

  • __DEV__

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

\ No newline at end of file diff --git a/releases/0.47/docs/keyboard.html b/releases/0.47/docs/keyboard.html new file mode 100644 index 00000000000..29ba80237af --- /dev/null +++ b/releases/0.47/docs/keyboard.html @@ -0,0 +1,55 @@ +Keyboard

Keyboard #

Keyboard module to control keyboard events.

Usage #

The Keyboard module allows you to listen for native events and react to them, as +well as make changes to the keyboard, like dismissing it.

import React, { Component } from 'react'; +import { Keyboard, TextInput } from 'react-native'; + +class Example extends Component { + componentWillMount () { + this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow); + this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide); + } + + componentWillUnmount () { + this.keyboardDidShowListener.remove(); + this.keyboardDidHideListener.remove(); + } + + _keyboardDidShow () { + alert('Keyboard Shown'); + } + + _keyboardDidHide () { + alert('Keyboard Hidden'); + } + + render() { + return ( + <TextInput + onSubmitEditing={Keyboard.dismiss} + /> + ); + } +}

Methods #

static addListener(eventName, callback) #

The addListener function connects a JavaScript function to an identified native +keyboard notification event.

This function then returns the reference to the listener.

@param {string} eventName The nativeEvent is the string that identifies the event you're listening for. This +can be any of the following:

  • keyboardWillShow
  • keyboardDidShow
  • keyboardWillHide
  • keyboardDidHide
  • keyboardWillChangeFrame
  • keyboardDidChangeFrame

Note that if you set android:windowSoftInputMode to adjustResize or adjustNothing, +only keyboardDidShow and keyboardDidHide events will be available on Android. +keyboardWillShow as well as keyboardWillHide are generally not available on Android +since there is no native corresponding event.

@param {function} callback function to be called when the event fires.

static removeListener(eventName, callback) #

Removes a specific listener.

@param {string} eventName The nativeEvent is the string that identifies the event you're listening for. +@param {function} callback function to be called when the event fires.

static removeAllListeners(eventName) #

Removes all listeners for a specific event type.

@param {string} eventType The native event string listeners are watching which will be removed.

static dismiss() #

Dismisses the active keyboard and removes focus.

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

\ No newline at end of file diff --git a/releases/0.47/docs/keyboardavoidingview.html b/releases/0.47/docs/keyboardavoidingview.html new file mode 100644 index 00000000000..b639a06c47c --- /dev/null +++ b/releases/0.47/docs/keyboardavoidingview.html @@ -0,0 +1,21 @@ +KeyboardAvoidingView

KeyboardAvoidingView #

It is a component to solve the common problem of views that need to move out of the way of the virtual keyboard. +It can automatically adjust either its position or bottom padding based on the position of the keyboard.

Props #

behavior?: PropTypes.oneOf(['height', 'position', 'padding']) #

contentContainerStyle?: ViewPropTypes.style #

The style of the content container(View) when behavior is 'position'.

keyboardVerticalOffset?: PropTypes.number.isRequired #

This is the distance between the top of the user screen and the react native view, +may be non-zero in some use cases.

Methods #

relativeKeyboardHeight(keyboardFrame: object): #

onKeyboardChange(event: object) #

onLayout(event: object) #

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

\ No newline at end of file diff --git a/releases/0.47/docs/layout-props.html b/releases/0.47/docs/layout-props.html new file mode 100644 index 00000000000..aec03db217a --- /dev/null +++ b/releases/0.47/docs/layout-props.html @@ -0,0 +1,269 @@ +Layout Props

Layout Props #

Props #

alignContent?: ReactPropTypes.oneOf([ + 'flex-start', + 'flex-end', + 'center', + 'stretch', + 'space-between', + 'space-around' +]) #

alignContent controls how rows align in the cross direction, + overriding the alignContent of the parent. + See https://developer.mozilla.org/en-US/docs/Web/CSS/align-content + for more details.

alignItems?: ReactPropTypes.oneOf([ + 'flex-start', + 'flex-end', + 'center', + 'stretch', + 'baseline' +]) #

alignItems aligns children in the cross direction. + For example, if children are flowing vertically, alignItems + controls how they align horizontally. + It works like align-items in CSS (default: stretch). + See https://developer.mozilla.org/en-US/docs/Web/CSS/align-items + for more details.

alignSelf?: ReactPropTypes.oneOf([ + 'auto', + 'flex-start', + 'flex-end', + 'center', + 'stretch', + 'baseline' +]) #

alignSelf controls how a child aligns in the cross direction, + overriding the alignItems of the parent. It works like align-self + in CSS (default: auto). + See https://developer.mozilla.org/en-US/docs/Web/CSS/align-self + for more details.

aspectRatio?: ReactPropTypes.number #

Aspect ratio control the size of the undefined dimension of a node. Aspect ratio is a +non-standard property only available in react native and not CSS.

  • On a node with a set width/height aspect ratio control the size of the unset dimension
  • On a node with a set flex basis aspect ratio controls the size of the node in the cross axis +if unset
  • On a node with a measure function aspect ratio works as though the measure function measures +the flex basis
  • On a node with flex grow/shrink aspect ratio controls the size of the node in the cross axis +if unset
  • Aspect ratio takes min/max dimensions into account

borderBottomWidth?: ReactPropTypes.number #

borderBottomWidth works like border-bottom-width in CSS. +See https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-width +for more details.

borderLeftWidth?: ReactPropTypes.number #

borderLeftWidth works like border-left-width in CSS. +See https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-width +for more details.

borderRightWidth?: ReactPropTypes.number #

borderRightWidth works like border-right-width in CSS. +See https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-width +for more details.

borderTopWidth?: ReactPropTypes.number #

borderTopWidth works like border-top-width in CSS. +See https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-width +for more details.

borderWidth?: ReactPropTypes.number #

borderWidth works like border-width in CSS. +See https://developer.mozilla.org/en-US/docs/Web/CSS/border-width +for more details.

bottom?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

bottom is the number of logical pixels to offset the bottom edge of + this component.

It works similarly to bottom in CSS, but in React Native you + must use points or percentages. Ems and other units are not supported.

See https://developer.mozilla.org/en-US/docs/Web/CSS/bottom + for more details of how bottom affects layout.

display?: ReactPropTypes.oneOf([ + 'none', + 'flex', +]) #

display sets the display type of this component.

It works similarly to display in CSS, but only support 'flex' and 'none'. + 'flex' is the default.

flex?: ReactPropTypes.number #

In React Native flex does not work the same way that it does in CSS. + flex is a number rather than a string, and it works + according to the Yoga library + at https://github.com/facebook/yoga

When flex is a positive number, it makes the component flexible + and it will be sized proportional to its flex value. So a + component with flex set to 2 will take twice the space as a + component with flex set to 1.

When flex is 0, the component is sized according to width + and height and it is inflexible.

When flex is -1, the component is normally sized according + width and height. However, if there's not enough space, + the component will shrink to its minWidth and minHeight.

flexGrow, flexShrink, and flexBasis work the same as in CSS.

flexBasis?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

flexDirection?: ReactPropTypes.oneOf([ + 'row', + 'row-reverse', + 'column', + 'column-reverse' +]) #

flexDirection controls which directions children of a container go. + row goes left to right, column goes top to bottom, and you may + be able to guess what the other two do. It works like flex-direction + in CSS, except the default is column. + See https://developer.mozilla.org/en-US/docs/Web/CSS/flex-direction + for more details.

flexGrow?: ReactPropTypes.number #

flexShrink?: ReactPropTypes.number #

flexWrap?: ReactPropTypes.oneOf([ + 'wrap', + 'nowrap' +]) #

flexWrap controls whether children can wrap around after they + hit the end of a flex container. + It works like flex-wrap in CSS (default: nowrap). + See https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap + for more details.

height?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

height sets the height of this component.

It works similarly to height in CSS, but in React Native you + must use points or percentages. Ems and other units are not supported. + See https://developer.mozilla.org/en-US/docs/Web/CSS/height for more details.

justifyContent?: ReactPropTypes.oneOf([ + 'flex-start', + 'flex-end', + 'center', + 'space-between', + 'space-around' +]) #

justifyContent aligns children in the main direction. + For example, if children are flowing vertically, justifyContent + controls how they align vertically. + It works like justify-content in CSS (default: flex-start). + See https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content + for more details.

left?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

left is the number of logical pixels to offset the left edge of + this component.

It works similarly to left in CSS, but in React Native you + must use points or percentages. Ems and other units are not supported.

See https://developer.mozilla.org/en-US/docs/Web/CSS/left + for more details of how left affects layout.

margin?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

Setting margin has the same effect as setting each of + marginTop, marginLeft, marginBottom, and marginRight. + See https://developer.mozilla.org/en-US/docs/Web/CSS/margin + for more details.

marginBottom?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

marginBottom works like margin-bottom in CSS. + See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-bottom + for more details.

marginHorizontal?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

Setting marginHorizontal has the same effect as setting + both marginLeft and marginRight.

marginLeft?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

marginLeft works like margin-left in CSS. + See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-left + for more details.

marginRight?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

marginRight works like margin-right in CSS. + See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-right + for more details.

marginTop?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

marginTop works like margin-top in CSS. + See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-top + for more details.

marginVertical?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

Setting marginVertical has the same effect as setting both + marginTop and marginBottom.

maxHeight?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

maxHeight is the maximum height for this component, in logical pixels.

It works similarly to max-height in CSS, but in React Native you + must use points or percentages. Ems and other units are not supported.

See https://developer.mozilla.org/en-US/docs/Web/CSS/max-height + for more details.

maxWidth?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

maxWidth is the maximum width for this component, in logical pixels.

It works similarly to max-width in CSS, but in React Native you + must use points or percentages. Ems and other units are not supported.

See https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + for more details.

minHeight?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

minHeight is the minimum height for this component, in logical pixels.

It works similarly to min-height in CSS, but in React Native you + must use points or percentages. Ems and other units are not supported.

See https://developer.mozilla.org/en-US/docs/Web/CSS/min-height + for more details.

minWidth?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

minWidth is the minimum width for this component, in logical pixels.

It works similarly to min-width in CSS, but in React Native you + must use points or percentages. Ems and other units are not supported.

See https://developer.mozilla.org/en-US/docs/Web/CSS/min-width + for more details.

overflow?: ReactPropTypes.oneOf([ + 'visible', + 'hidden', + 'scroll', +]) #

overflow controls how a children are measured and displayed. + overflow: hidden causes views to be clipped while overflow: scroll + causes views to be measured independently of their parents main axis. + It works like overflow in CSS (default: visible). + See https://developer.mozilla.org/en/docs/Web/CSS/overflow + for more details. + overflow: visible only works on iOS. On Android, all views will clip + their children.

padding?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

Setting padding has the same effect as setting each of + paddingTop, paddingBottom, paddingLeft, and paddingRight. + See https://developer.mozilla.org/en-US/docs/Web/CSS/padding + for more details.

paddingBottom?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

paddingBottom works like padding-bottom in CSS. +See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-bottom +for more details.

paddingHorizontal?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

Setting paddingHorizontal is like setting both of + paddingLeft and paddingRight.

paddingLeft?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

paddingLeft works like padding-left in CSS. +See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-left +for more details.

paddingRight?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

paddingRight works like padding-right in CSS. +See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-right +for more details.

paddingTop?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

paddingTop works like padding-top in CSS. +See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-top +for more details.

paddingVertical?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

Setting paddingVertical is like setting both of + paddingTop and paddingBottom.

position?: ReactPropTypes.oneOf([ + 'absolute', + 'relative' +]) #

position in React Native is similar to regular CSS, but + everything is set to relative by default, so absolute + positioning is always just relative to the parent.

If you want to position a child using specific numbers of logical + pixels relative to its parent, set the child to have absolute + position.

If you want to position a child relative to something + that is not its parent, just don't use styles for that. Use the + component tree.

See https://github.com/facebook/yoga + for more details on how position differs between React Native + and CSS.

right?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

right is the number of logical pixels to offset the right edge of + this component.

It works similarly to right in CSS, but in React Native you + must use points or percentages. Ems and other units are not supported.

See https://developer.mozilla.org/en-US/docs/Web/CSS/right + for more details of how right affects layout.

top?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

top is the number of logical pixels to offset the top edge of + this component.

It works similarly to top in CSS, but in React Native you + must use points or percentages. Ems and other units are not supported.

See https://developer.mozilla.org/en-US/docs/Web/CSS/top + for more details of how top affects layout.

width?: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string, +]) #

width sets the width of this component.

It works similarly to width in CSS, but in React Native you + must use points or percentages. Ems and other units are not supported. + See https://developer.mozilla.org/en-US/docs/Web/CSS/width for more details.

zIndex?: ReactPropTypes.number #

zIndex controls which components display on top of others. + Normally, you don't use zIndex. Components render according to + their order in the document tree, so later components draw over + earlier ones. zIndex may be useful if you have animations or custom + modal interfaces where you don't want this behavior.

It works like the CSS z-index property - components with a larger + zIndex will render on top. Think of the z-direction like it's + pointing from the phone into your eyeball. + See https://developer.mozilla.org/en-US/docs/Web/CSS/z-index for + more details.

iosdirection?: ReactPropTypes.oneOf([ + 'inherit', + 'ltr', + 'rtl', +]) #

direction specifies the directional flow of the user interface. + The default is inherit, except for root node which will have + value based on the current locale. + See https://facebook.github.io/yoga/docs/rtl/ + for more details.

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

\ No newline at end of file diff --git a/releases/0.47/docs/layoutanimation.html b/releases/0.47/docs/layoutanimation.html new file mode 100644 index 00000000000..c3c6805bb74 --- /dev/null +++ b/releases/0.47/docs/layoutanimation.html @@ -0,0 +1,23 @@ +LayoutAnimation

LayoutAnimation #

Automatically animates views to their new positions when the +next layout happens.

A common way to use this API is to call it before calling setState.

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);

Methods #

static configureNext(config, onAnimationDidEnd?) #

Schedules an animation to happen on the next layout.

@param config Specifies animation properties:

  • duration in milliseconds
  • create, config for animating in new views (see Anim type)
  • update, config for animating views that have been updated +(see Anim type)

@param onAnimationDidEnd Called when the animation finished. +Only supported on iOS. +@param onError Called on error. Only supported on iOS.

static create(duration, type, creationProp) #

Helper for creating a config for configureNext.

static checkConfig(config, location, name) #

Properties #

Types: CallExpression #

Properties: CallExpression #

Presets: ObjectExpression #

easeInEaseOut: CallExpression #

linear: CallExpression #

spring: CallExpression #

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

\ No newline at end of file diff --git a/releases/0.47/docs/linking-libraries-ios.html b/releases/0.47/docs/linking-libraries-ios.html new file mode 100644 index 00000000000..c4d702bd2e2 --- /dev/null +++ b/releases/0.47/docs/linking-libraries-ios.html @@ -0,0 +1,40 @@ +Linking Libraries

Linking Libraries #

Not every app uses all the native capabilities, and including the code to support +all those features would impact the binary size... But we still want to make it +easy to add these features whenever you need them.

With that in mind we exposed many of these features as independent static libraries.

For most of the libs it will be as simple as dragging two files, sometimes a third +step will be necessary, but no more than that.

All the libraries we ship with React Native live on the Libraries folder in +the root of the repository. Some of them are pure JavaScript, and you only need +to require it. Other libraries also rely on some native code, in that case +you'll have to add these files to your app, otherwise the app will throw an +error as soon as you try to use the library.

Here the few steps to link your libraries that contain native code #

Automatic linking #

Step 1 #

Install a library with native dependencies:

$ npm install <library-with-native-dependencies> --save

Note: --save or --save-dev flag is very important for this step. React Native will link +your libs based on dependencies and devDependencies in your package.json file.

Step 2 #

Link your native dependencies:

$ react-native link

Done! All libraries with native dependencies should be successfully linked to your iOS/Android project.

Manual linking #

Step 1 #

If the library has native code, there must be a .xcodeproj file inside it's +folder. +Drag this file to your project on Xcode (usually under the Libraries group +on Xcode);

Step 2 #

Click on your main project file (the one that represents the .xcodeproj) +select Build Phases and drag the static library from the Products folder +inside the Library you are importing to Link Binary With Libraries

Step 3 #

Not every library will need this step, what you need to consider is:

Do I need to know the contents of the library at compile time?

What that means is, are you using this library on the native side or only in +JavaScript? If you are only using it in JavaScript, you are good to go!

This step is not necessary for libraries that we ship with React Native with the +exception of PushNotificationIOS and Linking.

In the case of the PushNotificationIOS for example, you have to call a method +on the library from your AppDelegate every time a new push notification is +received.

For that we need to know the library's headers. To achieve that you have to go +to your project's file, select Build Settings and search for Header Search +Paths. There you should include the path to your library (if it has relevant +files on subdirectories remember to make it recursive, like React on the +example).

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

\ No newline at end of file diff --git a/releases/0.47/docs/linking.html b/releases/0.47/docs/linking.html new file mode 100644 index 00000000000..ef07b76822d --- /dev/null +++ b/releases/0.47/docs/linking.html @@ -0,0 +1,93 @@ +Linking

Linking #

+ +

Linking gives you a general interface to interact with both incoming +and outgoing app links.

Basic Usage #

Handling deep links #

If your app was launched from an external url registered to your app you can +access and handle it from any component you want with

componentDidMount() { + Linking.getInitialURL().then((url) => { + if (url) { + console.log('Initial url is: ' + url); + } + }).catch(err => console.error('An error occurred', err)); +}

NOTE: For instructions on how to add support for deep linking on Android, +refer to Enabling Deep Links for App Content - Add Intent Filters for Your Deep Links.

If you wish to receive the intent in an existing instance of MainActivity, +you may set the launchMode of MainActivity to singleTask in +AndroidManifest.xml. See <activity> +documentation for more information.

<activity + android:name=".MainActivity" + android:launchMode="singleTask">

NOTE: On iOS, you'll need to link RCTLinking to your project by following +the steps described here. +If you also want to listen to incoming app links during your app's +execution, you'll need to add the following lines to your *AppDelegate.m:

// iOS 9.x or newer +#import <React/RCTLinkingManager.h> + +- (BOOL)application:(UIApplication *)application + openURL:(NSURL *)url + options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options +{ + return [RCTLinkingManager application:app openURL:url options:options]; +}

If you're targeting iOS 8.x or older, you can use the following code instead:

// iOS 8.x or older +#import <React/RCTLinkingManager.h> + +- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url + sourceApplication:(NSString *)sourceApplication annotation:(id)annotation +{ + return [RCTLinkingManager application:application openURL:url + sourceApplication:sourceApplication annotation:annotation]; +}

// If your app is using Universal Links, +you'll need to add the following code as well:

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity + restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler +{ + return [RCTLinkingManager application:application + continueUserActivity:userActivity + restorationHandler:restorationHandler]; +}

And then on your React component you'll be able to listen to the events on +Linking as follows

componentDidMount() { + Linking.addEventListener('url', this._handleOpenURL); +}, +componentWillUnmount() { + Linking.removeEventListener('url', this._handleOpenURL); +}, +_handleOpenURL(event) { + console.log(event.url); +}

Opening external links #

To start the corresponding activity for a link (web URL, email, contact etc.), call

Linking.openURL(url).catch(err => console.error('An error occurred', err));

If you want to check if any installed app can handle a given URL beforehand you can call

Linking.canOpenURL(url).then(supported => { + if (!supported) { + console.log('Can\'t handle url: ' + url); + } else { + return Linking.openURL(url); + } +}).catch(err => console.error('An error occurred', err));

Methods #

constructor() #

addEventListener(type, handler) #

Add a handler to Linking changes by listening to the url event type +and providing the handler

removeEventListener(type, handler) #

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

openURL(url) #

Try to open the given url with any of the installed apps.

You can use other URLs, like a location (e.g. "geo:37.484847,-122.148386" on Android +or "http://maps.apple.com/?ll=37.484847,-122.148386" on iOS), a contact, +or any other URL that can be opened with the installed apps.

The method returns a Promise object. If the user confirms the open dialog or the +url automatically opens, the promise is resolved. If the user cancels the open dialog +or there are no registered applications for the url, the promise is rejected.

NOTE: This method will fail if the system doesn't know how to open the specified URL. +If you're passing in a non-http(s) URL, it's best to check {@code canOpenURL} first.

NOTE: For web URLs, the protocol ("http://", "https://") must be set accordingly!

canOpenURL(url) #

Determine whether or not an installed app can handle a given URL.

NOTE: For web URLs, the protocol ("http://", "https://") must be set accordingly!

NOTE: As of iOS 9, your app needs to provide the LSApplicationQueriesSchemes key +inside Info.plist or canOpenURL will always return false.

@param URL the URL to open

getInitialURL() #

If the app launch was triggered by an app link, +it will give the link url, otherwise it will give null

NOTE: To support deep linking on Android, refer http://developer.android.com/training/app-indexing/deep-linking.html#handling-intents

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

\ No newline at end of file diff --git a/releases/0.47/docs/listview.html b/releases/0.47/docs/listview.html new file mode 100644 index 00000000000..80176de291c --- /dev/null +++ b/releases/0.47/docs/listview.html @@ -0,0 +1,95 @@ +ListView

ListView #

ListView - A core component designed for efficient display of vertically +scrolling lists of changing data. The minimal API is to create a +ListView.DataSource, populate it with a simple +array of data blobs, and instantiate a ListView component with that data +source and a renderRow callback which takes a blob from the data array and +returns a renderable component.

Minimal example:

class MyComponent extends Component { + constructor() { + super(); + const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); + this.state = { + dataSource: ds.cloneWithRows(['row 1', 'row 2']), + }; + } + + render() { + return ( + <ListView + dataSource={this.state.dataSource} + renderRow={(rowData) => <Text>{rowData}</Text>} + /> + ); + } +}

ListView also supports more advanced features, including sections with sticky +section headers, header and footer support, callbacks on reaching the end of +the available data (onEndReached) and on the set of rows that are visible +in the device viewport change (onChangeVisibleRows), and several +performance optimizations.

There are a few performance operations designed to make ListView scroll +smoothly while dynamically loading potentially very large (or conceptually +infinite) data sets:

  • Only re-render changed rows - the rowHasChanged function provided to the +data source tells the ListView if it needs to re-render a row because the +source data has changed - see ListViewDataSource for more details.

  • Rate-limited row rendering - By default, only one row is rendered per +event-loop (customizable with the pageSize prop). This breaks up the +work into smaller chunks to reduce the chance of dropping frames while +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?: 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?: 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?: 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?: 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?: 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?: 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?: 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?: 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?: 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?: 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 +not supported in conjunction with horizontal={true}. Only enabled by +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.

flashScrollIndicators() #

Displays the scroll indicators momentarily.

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

\ No newline at end of file diff --git a/releases/0.47/docs/listviewdatasource.html b/releases/0.47/docs/listviewdatasource.html new file mode 100644 index 00000000000..35aad5d61a9 --- /dev/null +++ b/releases/0.47/docs/listviewdatasource.html @@ -0,0 +1,59 @@ +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 +array of strings, or an object with rows nested inside section objects.

To update the data in the datasource, use cloneWithRows (or +cloneWithRowsAndSections if you care about sections). The data in the +data source is immutable, so you can't modify it directly. The clone methods +suck in the new data and compute a diff for each row so ListView knows +whether to re-render it or not.

In this example, a component receives data in chunks, handled by +_onDataArrived, which concats the new data onto the old data and updates the +data source. We use concat to create a new array - mutating this._data, +e.g. with this._data.push(newRowData), would be an error. _rowHasChanged +understands the shape of the row data and knows how to efficiently compare +it.

getInitialState: function() { + var ds = new ListViewDataSource({rowHasChanged: this._rowHasChanged}); + return {ds}; +}, +_onDataArrived(newData) { + this._data = this._data.concat(newData); + this.setState({ + ds: this.state.ds.cloneWithRows(this._data) + }); +}

Methods #

constructor(params) #

You can provide custom extraction and hasChanged functions for section +headers and rows. If absent, data will be extracted with the +defaultGetRowData and defaultGetSectionHeaderData functions.

The default extractor expects data of one of the following forms:

{ sectionID_1: { rowID_1: <rowData1>, ... }, ... }

or

{ sectionID_1: [ <rowData1>, <rowData2>, ... ], ... }

or

[ [ <rowData1>, <rowData2>, ... ], ... ]

The constructor takes in a params argument that can contain any of the +following:

  • getRowData(dataBlob, sectionID, rowID);
  • getSectionHeaderData(dataBlob, sectionID);
  • rowHasChanged(prevRowData, nextRowData);
  • sectionHeaderHasChanged(prevSectionData, nextSectionData);

cloneWithRows(dataBlob, rowIdentities) #

Clones this ListViewDataSource with the specified dataBlob and +rowIdentities. The dataBlob is just an arbitrary blob of data. At +construction an extractor to get the interesting information was defined +(or the default was used).

The rowIdentities is a 2D array of identifiers for rows. +ie. [['a1', 'a2'], ['b1', 'b2', 'b3'], ...]. If not provided, it's +assumed that the keys of the section data are the row identities.

Note: This function does NOT clone the data in this data source. It simply +passes the functions defined at construction to a new data source with +the data specified. If you wish to maintain the existing data you must +handle merging of old and new data separately and then pass that into +this function as the dataBlob.

cloneWithRowsAndSections(dataBlob, sectionIdentities, rowIdentities) #

This performs the same function as the cloneWithRows function but here +you also specify what your sectionIdentities are. If you don't care +about sections you should safely be able to use cloneWithRows.

sectionIdentities is an array of identifiers for sections. +ie. ['s1', 's2', ...]. If not provided, it's assumed that the +keys of dataBlob are the section identities.

Note: this returns a new object!

getRowCount() #

getRowAndSectionCount() #

rowShouldUpdate(sectionIndex, rowIndex) #

Returns if the row is dirtied and needs to be rerendered

getRowData(sectionIndex, rowIndex) #

Gets the data required to render the row.

getRowIDForFlatIndex(index) #

Gets the rowID at index provided if the dataSource arrays were flattened, +or null of out of range indexes.

getSectionIDForFlatIndex(index) #

Gets the sectionID at index provided if the dataSource arrays were flattened, +or null for out of range indexes.

getSectionLengths() #

Returns an array containing the number of rows in each section

sectionHeaderShouldUpdate(sectionIndex) #

Returns if the section header is dirtied and needs to be rerendered

getSectionHeaderData(sectionIndex) #

Gets the data required to render the section header

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

\ No newline at end of file diff --git a/releases/0.47/docs/modal.html b/releases/0.47/docs/modal.html new file mode 100644 index 00000000000..a04e1f82ea0 --- /dev/null +++ b/releases/0.47/docs/modal.html @@ -0,0 +1,69 @@ +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'; + +class ModalExample extends Component { + + state = { + modalVisible: false, + } + + setModalVisible(visible) { + this.setState({modalVisible: visible}); + } + + render() { + return ( + <View style={{marginTop: 22}}> + <Modal + animationType={"slide"} + transparent={false} + visible={this.state.modalVisible} + onRequestClose={() => {alert("Modal has been closed.")}} + > + <View style={{marginTop: 22}}> + <View> + <Text>Hello World!</Text> + + <TouchableHighlight onPress={() => { + this.setModalVisible(!this.state.modalVisible) + }}> + <Text>Hide Modal</Text> + </TouchableHighlight> + + </View> + </View> + </Modal> + + <TouchableHighlight onPress={() => { + this.setModalVisible(true) + }}> + <Text>Show Modal</Text> + </TouchableHighlight> + + </View> + ); + } +}

Props #

animated?: bool #

Deprecated

Use the animationType prop instead.

animationType?: PropTypes.oneOf(['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?: PropTypes.func #

The onShow prop allows passing a function that will be called once the modal has been shown.

transparent?: PropTypes.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?: PropTypes.bool #

The visible prop determines whether your modal is visible.

androidhardwareAccelerated?: PropTypes.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?: PropTypes.func #

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.

iospresentationStyle?: PropTypes.oneOf(['fullScreen', 'pageSheet', 'formSheet', 'overFullScreen']) #

The presentationStyle prop controls how the modal appears (generally on larger devices such as iPad or plus-sized iPhones). +See https://developer.apple.com/reference/uikit/uimodalpresentationstyle for details.

  • fullScreen covers the screen completely
  • pageSheet covers portrait-width view centered (only on larger devices)
  • formSheet covers narrow-width view centered (only on larger devices)
  • overFullScreen covers the screen completely, but allows transparency

Default is set to overFullScreen or fullScreen depending on transparent property.

iossupportedOrientations?: PropTypes.arrayOf(PropTypes.oneOf(['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. +When using presentationStyle of pageSheet or formSheet, this property will be ignored by iOS.

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

\ No newline at end of file diff --git a/releases/0.47/docs/more-resources.html b/releases/0.47/docs/more-resources.html new file mode 100644 index 00000000000..84a4b4e5642 --- /dev/null +++ b/releases/0.47/docs/more-resources.html @@ -0,0 +1,19 @@ +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 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.

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 2017 and React.js Conf 2016, and we'll probably have more conferences in the future, too. Stay tuned. You can also find a list of dedicated React Native conferences here.

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

\ No newline at end of file diff --git a/releases/0.47/docs/native-components-android.html b/releases/0.47/docs/native-components-android.html new file mode 100644 index 00000000000..413014b5dce --- /dev/null +++ b/releases/0.47/docs/native-components-android.html @@ -0,0 +1,103 @@ +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> { + + public static final String REACT_CLASS = "RCTImageView"; + + @Override + public String getName() { + return REACT_CLASS; + }

2. Implement method createViewInstance #

Views are created in the createViewInstance method, the view should initialize itself in its default state, any properties will be set via a follow up call to updateView.

@Override + public ReactImageView createViewInstance(ThemedReactContext context) { + return new ReactImageView(context, Fresco.newDraweeControllerBuilder(), mCallerContext); + }

3. Expose view property setters using @ReactProp (or @ReactPropGroup) annotation #

Properties that are to be reflected in JavaScript needs to be exposed as setter method annotated with @ReactProp (or @ReactPropGroup). Setter method should take view to be updated (of the current view type) as a first argument and property value as a second argument. Setter should be declared as a void method and should be public. Property type sent to JS is determined automatically based on the type of value argument of the setter. The following type of values are currently supported: boolean, int, float, double, String, Boolean, Integer, ReadableArray, ReadableMap.

Annotation @ReactProp has one obligatory argument name of type String. Name assigned to the @ReactProp annotation linked to the setter method is used to reference the property on JS side.

Except from name, @ReactProp annotation may take following optional arguments: defaultBoolean, defaultInt, defaultFloat. Those arguments should be of the corresponding primitive type (accordingly boolean, int, float) and the value provided will be passed to the setter method in case when the property that the setter is referencing has been removed from the component. Note that "default" values are only provided for primitive types, in case when setter is of some complex type, null will be provided as a default value in case when corresponding property gets removed.

Setter declaration requirements for methods annotated with @ReactPropGroup are different than for @ReactProp, please refer to the @ReactPropGroup annotation class docs for more information about it.

IMPORTANT! in ReactJS updating the property value will result in setter method call. Note that one of the ways we can update component is by removing properties that has been set before. In that case setter method will be called as well to notify view manager that property has changed. In that case "default" value will be provided (for primitive types "default" can value can be specified using defaultBoolean, defaultFloat, etc. arguments of @ReactProp annotation, for complex types setter will be called with value set to null).

@ReactProp(name = "src") + public void setSrc(ReactImageView view, @Nullable String src) { + view.setSource(src); + } + + @ReactProp(name = "borderRadius", defaultFloat = 0f) + public void setBorderRadius(ReactImageView view, float borderRadius) { + view.setBorderRadius(borderRadius); + } + + @ReactProp(name = ViewProps.RESIZE_MODE) + public void setResizeMode(ReactImageView view, @Nullable String resizeMode) { + view.setScaleType(ImageResizeMode.toScaleType(resizeMode)); + }

4. Register the ViewManager #

The final Java step is to register the ViewManager to the application, this happens in a similar way to Native Modules, via the applications package member function createViewManagers.

@Override + public List<ViewManager> createViewManagers( + ReactApplicationContext reactContext) { + return Arrays.<ViewManager>asList( + new ReactImageManager() + ); + }

5. Implement the JavaScript module #

The very final step is to create the JavaScript module that defines the interface layer between Java and JavaScript for the users of your new view. Much of the effort is handled by internal React code in Java and JavaScript and all that is left for you is to describe the propTypes.

// ImageView.js + +import PropTypes from 'prop-types'; +import { requireNativeComponent, View } from 'react-native'; + +var iface = { + name: 'ImageView', + propTypes: { + src: PropTypes.string, + borderRadius: PropTypes.number, + resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch']), + ...View.propTypes // include the default view properties + }, +}; + +module.exports = requireNativeComponent('RCTImageView', iface);

requireNativeComponent commonly takes two parameters, the first is the name of the native view and the second is an object that describes the component interface. The component interface should declare a friendly name for use in debug messages and must declare the propTypes reflected by the Native View. The propTypes are used for checking the validity of a user's use of the native view. Note that if you need your JavaScript component to do more than just specify a name and propTypes, like do custom event handling, you can wrap the native component in a normal react component. In that case, you want to pass in the wrapper component instead of iface to requireNativeComponent. This is illustrated in the MyCustomView example below.

Events #

So now we know how to expose native view components that we can control easily from JS, but how do we deal with events from the user, like pinch-zooms or panning? When a native event occurs the native code should issue an event to the JavaScript representation of the View, and the two views are linked with the value returned from the getId() method.

class MyCustomView extends View { + ... + public void onReceiveNativeEvent() { + WritableMap event = Arguments.createMap(); + event.putString("message", "MyMessage"); + ReactContext reactContext = (ReactContext)getContext(); + reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( + getId(), + "topChange", + event); + } +}

The event name topChange maps to the onChange callback prop in JavaScript (mappings are in UIManagerModuleConstants.java). This callback is invoked with the raw event, which we typically process in the wrapper component to make a simpler API:

// MyCustomView.js + +class MyCustomView extends React.Component { + constructor(props) { + super(props); + this._onChange = this._onChange.bind(this); + } + _onChange(event: Event) { + if (!this.props.onChangeMessage) { + return; + } + this.props.onChangeMessage(event.nativeEvent.message); + } + render() { + return <RCTMyCustomView {...this.props} onChange={this._onChange} />; + } +} +MyCustomView.propTypes = { + /** + * Callback that is called continuously when the user is dragging the map. + */ + onChangeMessage: PropTypes.func, + ... +}; + +var RCTMyCustomView = requireNativeComponent(`RCTMyCustomView`, MyCustomView, { + nativeOnly: {onChange: true} +});

Note the use of nativeOnly above. Sometimes you'll have some special properties that you need to expose for the native component, but don't actually want them as part of the API for the associated React component. For example, Switch has a custom onChange handler for the raw native event, and exposes an onValueChange handler property that is invoked with just the boolean value rather than the raw event (similar to onChangeMessage in the example above). Since you don't want these native only properties to be part of the API, you don't want to put them in propTypes, but if you don't you'll get an error. The solution is simply to call them out via the nativeOnly option.

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

\ No newline at end of file diff --git a/releases/0.47/docs/native-components-ios.html b/releases/0.47/docs/native-components-ios.html new file mode 100644 index 00000000000..a9348dc0259 --- /dev/null +++ b/releases/0.47/docs/native-components-ios.html @@ -0,0 +1,292 @@ +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> + +@interface RNTMapManager : RCTViewManager +@end + +@implementation RNTMapManager + +RCT_EXPORT_MODULE() + +- (UIView *)view +{ + return [[MKMapView alloc] init]; +} + +@end

Note: Do not attempt to set the frame or backgroundColor properties on the UIView instance that you vend through the -view method. React Native will overwrite the values set by your custom class in order to match your JavaScript component's layout props. If you need this granularity of control it might be better to wrap the UIView instance you want to style in another UIView and return the wrapper UIView instead. See Issue 2948 for more context.

In the example above, we prefixed our class name with RNT. Prefixes are used to avoid name collisions with other frameworks. Apple frameworks use two-letter prefixes, and React Native uses RCT as a prefix. In order to avoid name collisions, we recommend using a three-letter prefix other than RCT in your own classes.

Then you just need a little bit of JavaScript to make this a usable React component:

// MapView.js + +import { requireNativeComponent } from 'react-native'; + +// requireNativeComponent automatically resolves this to "RNTMapManager" +module.exports = requireNativeComponent('RNTMap', null);

This is now a fully-functioning native map view component in JavaScript, complete with pinch-zoom and other native gesture support. We can't really control it from JavaScript yet, though :(

Properties #

The first thing we can do to make this component more usable is to bridge over some native properties. Let's say we want to be able to disable pitch control and specify the visible region. Disabling pitch is a simple boolean, so we add this one line:

// RNTMapManager.m +RCT_EXPORT_VIEW_PROPERTY(pitchEnabled, BOOL)

Note that we explicitly specify the type as BOOL - React Native uses RCTConvert under the hood to convert all sorts of different data types when talking over the bridge, and bad values will show convenient "RedBox" errors to let you know there is an issue ASAP. When things are straightforward like this, the whole implementation is taken care of for you by this macro.

Now to actually disable pitch, we set the property in JS:

// MyApp.js +<MapView pitchEnabled={false} />

This isn't very well documented though - in order to know what properties are available and what values they accept, the client of your new component needs to dig through the Objective-C code. To make this better, let's make a wrapper component and document the interface with React PropTypes:

// MapView.js +import PropTypes from 'prop-types'; +import React from 'react'; +import { requireNativeComponent } from 'react-native'; + +class MapView extends React.Component { + render() { + return <RNTMap {...this.props} />; + } +} + +MapView.propTypes = { + /** + * When this property is set to `true` and a valid camera is associated + * with the map, the camera’s pitch angle is used to tilt the plane + * of the map. When this property is set to `false`, the camera’s pitch + * angle is ignored and the map is always displayed as if the user + * is looking straight down onto it. + */ + pitchEnabled: PropTypes.bool, +}; + +var RNTMap = requireNativeComponent('RNTMap', MapView); + +module.exports = MapView;

Now we have a nicely documented wrapper component that is easy to work with. Note that we changed the second argument to requireNativeComponent from null to the new MapView wrapper component. This allows the infrastructure to verify that the propTypes match the native props to reduce the chances of mismatches between the ObjC and JS code.

Next, let's add the more complex region prop. We start by adding the native code:

// RNTMapManager.m +RCT_CUSTOM_VIEW_PROPERTY(region, MKCoordinateRegion, RNTMap) +{ + [view setRegion:json ? [RCTConvert MKCoordinateRegion:json] : defaultView.region animated:YES]; +}

Ok, this is more complicated than the simple BOOL case we had before. Now we have a MKCoordinateRegion type that needs a conversion function, and we have custom code so that the view will animate when we set the region from JS. Within the function body that we provide, json refers to the raw value that has been passed from JS. There is also a view variable which gives us access to the manager's view instance, and a defaultView that we use to reset the property back to the default value if JS sends us a null sentinel.

You could write any conversion function you want for your view - here is the implementation for MKCoordinateRegion via two categories on RCTConvert:

@implementation RCTConvert(CoreLocation) + +RCT_CONVERTER(CLLocationDegrees, CLLocationDegrees, doubleValue); +RCT_CONVERTER(CLLocationDistance, CLLocationDistance, doubleValue); + ++ (CLLocationCoordinate2D)CLLocationCoordinate2D:(id)json +{ + json = [self NSDictionary:json]; + return (CLLocationCoordinate2D){ + [self CLLocationDegrees:json[@"latitude"]], + [self CLLocationDegrees:json[@"longitude"]] + }; +} + +@end + +@implementation RCTConvert(MapKit) + ++ (MKCoordinateSpan)MKCoordinateSpan:(id)json +{ + json = [self NSDictionary:json]; + return (MKCoordinateSpan){ + [self CLLocationDegrees:json[@"latitudeDelta"]], + [self CLLocationDegrees:json[@"longitudeDelta"]] + }; +} + ++ (MKCoordinateRegion)MKCoordinateRegion:(id)json +{ + return (MKCoordinateRegion){ + [self CLLocationCoordinate2D:json], + [self MKCoordinateSpan:json] + }; +}

These conversion functions are designed to safely process any JSON that the JS might throw at them by displaying "RedBox" errors and returning standard initialization values when missing keys or other developer errors are encountered.

To finish up support for the region prop, we need to document it in propTypes (or we'll get an error that the native prop is undocumented), then we can set it just like any other prop:

// MapView.js + +MapView.propTypes = { + /** + * When this property is set to `true` and a valid camera is associated + * with the map, the camera’s pitch angle is used to tilt the plane + * of the map. When this property is set to `false`, the camera’s pitch + * angle is ignored and the map is always displayed as if the user + * is looking straight down onto it. + */ + pitchEnabled: PropTypes.bool, + + /** + * The region to be displayed by the map. + * + * The region is defined by the center coordinates and the span of + * coordinates to display. + */ + region: PropTypes.shape({ + /** + * Coordinates for the center of the map. + */ + latitude: PropTypes.number.isRequired, + longitude: PropTypes.number.isRequired, + + /** + * Distance between the minimum and the maximum latitude/longitude + * to be displayed. + */ + latitudeDelta: PropTypes.number.isRequired, + longitudeDelta: PropTypes.number.isRequired, + }), +}; + +// MyApp.js + + render() { + var region = { + latitude: 37.48, + longitude: -122.16, + latitudeDelta: 0.1, + longitudeDelta: 0.1, + }; + return <MapView region={region} />; + }

Here you can see that the shape of the region is explicit in the JS documentation - ideally we could codegen some of this stuff, but that's not happening yet.

Sometimes you'll have some special properties that you need to expose for the native component, but don't actually want them as part of the API for the associated React component. For example, Switch has a custom onChange handler for the raw native event, and exposes an onValueChange handler property that is invoked with just the boolean value rather than the raw event. Since you don't want these native only properties to be part of the API, you don't want to put them in propTypes, but if you don't you'll get an error. The solution is simply to call them out via the nativeOnly option, e.g.

var RCTSwitch = requireNativeComponent('RCTSwitch', Switch, { + nativeOnly: { onChange: true } +});

Events #

So now we have a native map component that we can control easily from JS, but how do we deal with events from the user, like pinch-zooms or panning to change the visible region? The key is to declare an event handler property on RNTMapManager, make it a delegate for all the views it vends, and forward events to JS by calling the event handler block from the native view. This looks like so (simplified from the full implementation):

// RNTMap.h + +#import <MapKit/MapKit.h> + +#import <React/RCTComponent.h> + +@interface RNTMap: MKMapView + +@property (nonatomic, copy) RCTBubblingEventBlock onChange; + +@end
// RNTMap.m + +#import "RNTMap.h" + +@implementation RNTMap + +@end
// RNTMapManager.m + +#import "RNTMapManager.h" + +#import <MapKit/MapKit.h> + +#import "RNTMap.h" +#import <React/UIView+React.h> + +@interface RNTMapManager() <MKMapViewDelegate> +@end + +@implementation RNTMapManager + +RCT_EXPORT_MODULE() + +RCT_EXPORT_VIEW_PROPERTY(onChange, RCTBubblingEventBlock) + +- (UIView *)view +{ + RNTMap *map = [RNTMap new]; + map.delegate = self; + return map; +} + +#pragma mark MKMapViewDelegate + +- (void)mapView:(RNTMap *)mapView regionDidChangeAnimated:(BOOL)animated +{ + if (!mapView.onChange) { + return; + } + + MKCoordinateRegion region = mapView.region; + mapView.onChange(@{ + @"region": @{ + @"latitude": @(region.center.latitude), + @"longitude": @(region.center.longitude), + @"latitudeDelta": @(region.span.latitudeDelta), + @"longitudeDelta": @(region.span.longitudeDelta), + } + }); +}

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(props) { + super(props) + this._onChange = this._onChange.bind(this); + } + _onChange(event: Event) { + if (!this.props.onRegionChange) { + return; + } + this.props.onRegionChange(event.nativeEvent); + } + render() { + return <RNTMap {...this.props} onChange={this._onChange} />; + } +} +MapView.propTypes = { + /** + * Callback that is called continuously when the user is dragging the map. + */ + onChange: PropTypes.func, + ... +}; + +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('AwesomeProject', () => 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; +... + render: function() { + return ( + <View style={this.props.style}> + <RCTDatePickerIOS + ref={DATEPICKER} + style={styles.rkDatePickerIOS} + ... + /> + </View> + ); + } +}); + +var styles = StyleSheet.create({ + rkDatePickerIOS: { + height: RCTDatePickerIOSConsts.ComponentHeight, + width: RCTDatePickerIOSConsts.ComponentWidth, + }, +});

The RCTDatePickerIOSConsts constants are exported from native by grabbing the actual frame of the native component like so:

// RCTDatePickerManager.m + +- (NSDictionary *)constantsToExport +{ + UIDatePicker *dp = [[UIDatePicker alloc] init]; + [dp layoutIfNeeded]; + + return @{ + @"ComponentHeight": @(CGRectGetHeight(dp.frame)), + @"ComponentWidth": @(CGRectGetWidth(dp.frame)), + @"DatePickerModes": @{ + @"time": @(UIDatePickerModeTime), + @"date": @(UIDatePickerModeDate), + @"datetime": @(UIDatePickerModeDateAndTime), + } + }; +}

This guide covered many of the aspects of bridging over custom native components, but there is even more you might need to consider, such as custom hooks for inserting and laying out subviews. If you want to go even deeper, check out the actual RCTMapManager and other components in the source code.

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

\ No newline at end of file diff --git a/releases/0.47/docs/native-modules-android.html b/releases/0.47/docs/native-modules-android.html new file mode 100644 index 00000000000..0647ebe3702 --- /dev/null +++ b/releases/0.47/docs/native-modules-android.html @@ -0,0 +1,300 @@ +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; + +import com.facebook.react.bridge.NativeModule; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.bridge.ReactContext; +import com.facebook.react.bridge.ReactContextBaseJavaModule; +import com.facebook.react.bridge.ReactMethod; + +import java.util.Map; + +public class ToastModule extends ReactContextBaseJavaModule { + + private static final String DURATION_SHORT_KEY = "SHORT"; + private static final String DURATION_LONG_KEY = "LONG"; + + public ToastModule(ReactApplicationContext reactContext) { + super(reactContext); + } +}

ReactContextBaseJavaModule requires that a method called getName is implemented. The purpose of this method is to return the string name of the NativeModule which represents this class in JavaScript. So here we will call this ToastAndroid so that we can access it through React.NativeModules.ToastAndroid in JavaScript.

@Override + public String getName() { + return "ToastAndroid"; + }

An optional method called getConstants returns the constant values exposed to JavaScript. Its implementation is not required but is very useful to key pre-defined values that need to be communicated from JavaScript to Java in sync.

@Override + public Map<String, Object> getConstants() { + final Map<String, Object> constants = new HashMap<>(); + constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT); + constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG); + return constants; + }

To expose a method to JavaScript a Java method must be annotated using @ReactMethod. The return type of bridge methods is always void. React Native bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting events (see below).

@ReactMethod + public void show(String message, int duration) { + Toast.makeText(getReactApplicationContext(), message, duration).show(); + }

Argument Types #

The following argument types are supported for methods annotated with @ReactMethod and they directly map to their JavaScript equivalents

Boolean -> Bool +Integer -> Number +Double -> Number +Float -> Number +String -> String +Callback -> function +ReadableMap -> Object +ReadableArray -> Array

Read more about ReadableMap and ReadableArray

Register the Module #

The last step within Java is to register the Module; this happens in the createNativeModules of your apps package. If a module is not registered it will not be available from JavaScript.

package com.facebook.react.modules.toast; + +import com.facebook.react.ReactPackage; +import com.facebook.react.bridge.NativeModule; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.uimanager.ViewManager; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class AnExampleReactPackage implements ReactPackage { + + @Override + public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { + return Collections.emptyList(); + } + + @Override + public List<NativeModule> createNativeModules( + ReactApplicationContext reactContext) { + List<NativeModule> modules = new ArrayList<>(); + + modules.add(new ToastModule(reactContext)); + + return modules; + } + +}

The package needs to be provided in the getPackages method of the MainApplication.java file. This file exists under the android folder in your react-native application directory. The path to this file is: android/app/src/main/java/com/your-app-name/MainApplication.java.

protected List<ReactPackage> getPackages() { + return Arrays.<ReactPackage>asList( + new MainReactPackage(), + new AnExampleReactPackage()); // <-- Add this line with your package name. +}

To make it simpler to access your new functionality from JavaScript, it is common to wrap the native module in a JavaScript module. This is not necessary but saves the consumers of your library the need to pull it off of NativeModules each time. This JavaScript file also becomes a good location for you to add any JavaScript side functionality.

'use strict'; +/** + * 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 + */ +import { NativeModules } from 'react-native'; +module.exports = NativeModules.ToastAndroid;

Now, from your other JavaScript file you can call the method like this:

import ToastAndroid from './ToastAndroid'; + +ToastAndroid.show('Awesome', ToastAndroid.SHORT);

Beyond Toasts #

Callbacks #

Native modules also support a special kind of argument - a callback. In most cases it is used to provide the function call result to JavaScript.

public class UIManagerModule extends ReactContextBaseJavaModule { + +... + + @ReactMethod + public void measureLayout( + int tag, + int ancestorTag, + Callback errorCallback, + Callback successCallback) { + try { + measureLayout(tag, ancestorTag, mMeasureBuffer); + float relativeX = PixelUtil.toDIPFromPixel(mMeasureBuffer[0]); + float relativeY = PixelUtil.toDIPFromPixel(mMeasureBuffer[1]); + float width = PixelUtil.toDIPFromPixel(mMeasureBuffer[2]); + float height = PixelUtil.toDIPFromPixel(mMeasureBuffer[3]); + successCallback.invoke(relativeX, relativeY, width, height); + } catch (IllegalViewOperationException e) { + errorCallback.invoke(e.getMessage()); + } + } + +...

This method would be accessed in JavaScript using:

UIManager.measureLayout( + 100, + 100, + (msg) => { + console.log(msg); + }, + (x, y, width, height) => { + console.log(x + ':' + y + ':' + width + ':' + height); + } +);

A native module is supposed to invoke its callback only once. It can, however, store the callback and invoke it later.

It is very important to highlight that the callback is not invoked immediately after the native function completes - remember that bridge communication is asynchronous, and this too is tied to the run loop.

Promises #

Native modules can also fulfill a promise, which can simplify your code, especially when using ES2016's async/await syntax. When the last parameter of a bridged native method is a Promise, its corresponding JS method will return a JS Promise object.

Refactoring the above code to use a promise instead of callbacks looks like this:

import com.facebook.react.bridge.Promise; + +public class UIManagerModule extends ReactContextBaseJavaModule { + +... + private static final String E_LAYOUT_ERROR = "E_LAYOUT_ERROR"; + @ReactMethod + public void measureLayout( + int tag, + int ancestorTag, + Promise promise) { + try { + measureLayout(tag, ancestorTag, mMeasureBuffer); + + WritableMap map = Arguments.createMap(); + + map.putDouble("relativeX", PixelUtil.toDIPFromPixel(mMeasureBuffer[0])); + map.putDouble("relativeY", PixelUtil.toDIPFromPixel(mMeasureBuffer[1])); + map.putDouble("width", PixelUtil.toDIPFromPixel(mMeasureBuffer[2])); + map.putDouble("height", PixelUtil.toDIPFromPixel(mMeasureBuffer[3])); + + promise.resolve(map); + } catch (IllegalViewOperationException e) { + promise.reject(E_LAYOUT_ERROR, e); + } + } + +...

The JavaScript counterpart of this method returns a Promise. This means you can use the await keyword within an async function to call it and wait for its result:

async function measureLayout() { + try { + var { + relativeX, + relativeY, + width, + height, + } = await UIManager.measureLayout(100, 100); + + console.log(relativeX + ':' + relativeY + ':' + width + ':' + height); + } catch (e) { + console.error(e); + } +} + +measureLayout();

Threading #

Native modules should not have any assumptions about what thread they are being called on, as the current assignment is subject to change in the future. If a blocking call is required, the heavy work should be dispatched to an internally managed worker thread, and any callbacks distributed from there.

Sending Events to JavaScript #

Native modules can signal events to JavaScript without being invoked directly. The easiest way to do this is to use the RCTDeviceEventEmitter which can be obtained from the ReactContext as in the code snippet below.

... +private void sendEvent(ReactContext reactContext, + String eventName, + @Nullable WritableMap params) { + reactContext + .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) + .emit(eventName, params); +} +... +WritableMap params = Arguments.createMap(); +... +sendEvent(reactContext, "keyboardWillShow", params);

JavaScript modules can then register to receive events by addListenerOn using the Subscribable mixin.

import { DeviceEventEmitter } from 'react-native'; +... + +var ScrollResponderMixin = { + mixins: [Subscribable.Mixin], + + + componentWillMount: function() { + ... + this.addListenerOn(DeviceEventEmitter, + 'keyboardWillShow', + this.scrollResponderKeyboardWillShow); + ... + }, + scrollResponderKeyboardWillShow:function(e: Event) { + this.keyboardWillOpenTo = e; + this.props.onKeyboardWillShow && this.props.onKeyboardWillShow(e); + },

You can also directly use the DeviceEventEmitter module to listen for events.

... +componentWillMount: function() { + DeviceEventEmitter.addListener('keyboardWillShow', function(e: Event) { + // handle event. + }); +} +...

Getting activity result from startActivityForResult #

You'll need to listen to onActivityResult if you want to get results from an activity you started with startActivityForResult. To do this, you must extend BaseActivityEventListener or implement ActivityEventListener. The former is preferred as it is more resilient to API changes. Then, you need to register the listener in the module's constructor,

reactContext.addActivityEventListener(mActivityResultListener);

Now you can listen to onActivityResult by implementing the following method:

@Override +public void onActivityResult( + final Activity activity, + final int requestCode, + final int resultCode, + final Intent intent) { + // Your logic here +}

We will implement a simple image picker to demonstrate this. The image picker will expose the method pickImage to JavaScript, which will return the path of the image when called.

public class ImagePickerModule extends ReactContextBaseJavaModule { + + private static final int IMAGE_PICKER_REQUEST = 467081; + private static final String E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST"; + private static final String E_PICKER_CANCELLED = "E_PICKER_CANCELLED"; + private static final String E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER"; + private static final String E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND"; + + private Promise mPickerPromise; + + private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() { + + @Override + public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) { + if (requestCode == IMAGE_PICKER_REQUEST) { + if (mPickerPromise != null) { + if (resultCode == Activity.RESULT_CANCELED) { + mPickerPromise.reject(E_PICKER_CANCELLED, "Image picker was cancelled"); + } else if (resultCode == Activity.RESULT_OK) { + Uri uri = intent.getData(); + + if (uri == null) { + mPickerPromise.reject(E_NO_IMAGE_DATA_FOUND, "No image data found"); + } else { + mPickerPromise.resolve(uri.toString()); + } + } + + mPickerPromise = null; + } + } + } + }; + + public ImagePickerModule(ReactApplicationContext reactContext) { + super(reactContext); + + // Add the listener for `onActivityResult` + reactContext.addActivityEventListener(mActivityEventListener); + } + + @Override + public String getName() { + return "ImagePickerModule"; + } + + @ReactMethod + public void pickImage(final Promise promise) { + Activity currentActivity = getCurrentActivity(); + + if (currentActivity == null) { + promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist"); + return; + } + + // Store the promise to resolve/reject when picker returns data + mPickerPromise = promise; + + try { + final Intent galleryIntent = new Intent(Intent.ACTION_PICK); + + galleryIntent.setType("image/*"); + + final Intent chooserIntent = Intent.createChooser(galleryIntent, "Pick an image"); + + currentActivity.startActivityForResult(chooserIntent, IMAGE_PICKER_REQUEST); + } catch (Exception e) { + mPickerPromise.reject(E_FAILED_TO_SHOW_PICKER, e); + mPickerPromise = null; + } + } +}

Listening to LifeCycle events #

Listening to the activity's LifeCycle events such as onResume, onPause etc. is very similar to how we implemented ActivityEventListener. The module must implement LifecycleEventListener. Then, you need to register a listener in the module's constructor,

reactContext.addLifecycleEventListener(this);

Now you can listen to the activity's LifeCycle events by implementing the following methods:

@Override +public void onHostResume() { + // Activity `onResume` +} + +@Override +public void onHostPause() { + // Activity `onPause` +} + +@Override +public void onHostDestroy() { + // Activity `onDestroy` +}

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

\ No newline at end of file diff --git a/releases/0.47/docs/native-modules-ios.html b/releases/0.47/docs/native-modules-ios.html new file mode 100644 index 00000000000..c3b7646b262 --- /dev/null +++ b/releases/0.47/docs/native-modules-ios.html @@ -0,0 +1,212 @@ +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> +@end

In addition to implementing the RCTBridgeModule protocol, your class must also include the RCT_EXPORT_MODULE() macro. This takes an optional argument that specifies the name that the module will be accessible as in your JavaScript code (more on this later). If you do not specify a name, the JavaScript module name will match the Objective-C class name.

// CalendarManager.m +@implementation CalendarManager + +// To export a module named CalendarManager +RCT_EXPORT_MODULE(); + +// This would name the module AwesomeCalendarManager instead +// RCT_EXPORT_MODULE(AwesomeCalendarManager); + +@end

React Native will not expose any methods of CalendarManager to JavaScript unless explicitly told to. This is done using the RCT_EXPORT_METHOD() macro:

#import "CalendarManager.h" +#import <React/RCTLog.h> + +@implementation CalendarManager + +RCT_EXPORT_MODULE(); + +RCT_EXPORT_METHOD(addEvent:(NSString *)name location:(NSString *)location) +{ + RCTLogInfo(@"Pretending to create an event %@ at %@", name, location); +}

Now, from your JavaScript file you can call the method like this:

import { NativeModules } from 'react-native'; +var CalendarManager = NativeModules.CalendarManager; +CalendarManager.addEvent('Birthday Party', '4 Privet Drive, Surrey');

NOTE: JavaScript method names

The name of the method exported to JavaScript is the native method's name up to the first colon. React Native also defines a macro called RCT_REMAP_METHOD() to specify the JavaScript method's name. This is useful when multiple native methods are the same up to the first colon and would have conflicting JavaScript names.

The CalendarManager module is instantiated on the Objective-C side using a [CalendarManager new] call. The return type of bridge methods is always void. React Native bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting events (see below).

Argument Types #

RCT_EXPORT_METHOD supports all standard JSON object types, such as:

  • string (NSString)
  • number (NSInteger, float, double, CGFloat, NSNumber)
  • boolean (BOOL, NSNumber)
  • array (NSArray) of any types from this list
  • object (NSDictionary) with string keys and values of any type from this list
  • function (RCTResponseSenderBlock)

But it also works with any type that is supported by the RCTConvert class (see RCTConvert for details). The RCTConvert helper functions all accept a JSON value as input and map it to a native Objective-C type or class.

In our CalendarManager example, we need to pass the event date to the native method. We can't send JavaScript Date objects over the bridge, so we need to convert the date to a string or number. We could write our native function like this:

RCT_EXPORT_METHOD(addEvent:(NSString *)name location:(NSString *)location date:(nonnull NSNumber *)secondsSinceUnixEpoch) +{ + NSDate *date = [RCTConvert NSDate:secondsSinceUnixEpoch]; +}

or like this:

RCT_EXPORT_METHOD(addEvent:(NSString *)name location:(NSString *)location date:(NSString *)ISO8601DateString) +{ + NSDate *date = [RCTConvert NSDate:ISO8601DateString]; +}

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 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) +{ + NSString *location = [RCTConvert NSString:details[@"location"]]; + NSDate *time = [RCTConvert NSDate:details[@"time"]]; + ... +}

and call it from JavaScript:

CalendarManager.addEvent('Birthday Party', { + location: '4 Privet Drive, Surrey', + time: date.getTime(), + description: '...' +})

NOTE: About array and map

Objective-C doesn't provide any guarantees about the types of values in these structures. Your native module might expect an array of strings, but if JavaScript calls your method with an array containing numbers and strings, you'll get an NSArray containing a mix of NSNumber and NSString. For arrays, RCTConvert provides some typed collections you can use in your method declaration, such as NSStringArray, or UIColorArray. For maps, it is the developer's responsibility to check the value types individually by manually calling RCTConvert helper methods.

Callbacks #

WARNING

This section is more experimental than others because we don't have a solid set of best practices around callbacks yet.

Native modules also supports a special kind of argument- a callback. In most cases it is used to provide the function call result to JavaScript.

RCT_EXPORT_METHOD(findEvents:(RCTResponseSenderBlock)callback) +{ + NSArray *events = ... + callback(@[[NSNull null], events]); +}

RCTResponseSenderBlock accepts only one argument - an array of parameters to pass to the JavaScript callback. In this case we use Node's convention to make the first parameter an error object (usually null when there is no error) and the rest are the results of the function.

CalendarManager.findEvents((error, events) => { + if (error) { + console.error(error); + } else { + 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, + findEventsWithResolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) +{ + NSArray *events = ... + if (events) { + resolve(events); + } else { + NSError *error = ... + reject(@"no_events", @"There were no events", error); + } +}

The JavaScript counterpart of this method returns a Promise. This means you can use the await keyword within an async function to call it and wait for its result:

async function updateEvents() { + try { + var events = await CalendarManager.findEvents(); + + this.setState({ events }); + } catch (e) { + console.error(e); + } +} + +updateEvents();

Threading #

The native module should not have any assumptions about what thread it is being called on. React Native invokes native modules methods on a separate serial GCD queue, but this is an implementation detail and might change. The - (dispatch_queue_t)methodQueue method allows the native module to specify which queue its methods should be run on. For example, if it needs to use a main-thread-only iOS API, it should specify this via:

- (dispatch_queue_t)methodQueue +{ + return dispatch_get_main_queue(); +}

Similarly, if an operation may take a long time to complete, the native module should not block and can specify it's own queue to run operations on. For example, the RCTAsyncLocalStorage module creates its own queue so the React queue isn't blocked waiting on potentially slow disk access:

- (dispatch_queue_t)methodQueue +{ + return dispatch_queue_create("com.facebook.React.AsyncLocalStorageQueue", DISPATCH_QUEUE_SERIAL); +}

The specified methodQueue will be shared by all of the methods in your module. If just one of your methods is long-running (or needs to be run on a different queue than the others for some reason), you can use dispatch_async inside the method to perform that particular method's code on another queue, without affecting the others:

RCT_EXPORT_METHOD(doSomethingExpensive:(NSString *)param callback:(RCTResponseSenderBlock)callback) +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + // Call long-running code on background thread + ... + // You can invoke callback from any thread/queue + callback(@[...]); + }); +}

NOTE: Sharing dispatch queues between modules

The methodQueue method will be called once when the module is initialized, and then retained by the bridge, so there is no need to retain the queue yourself, unless you wish to make use of it within your module. However, if you wish to share the same queue between multiple modules then you will need to ensure that you retain and return the same queue instance for each of them; merely returning a queue of the same name for each won't work.

Dependency Injection #

The bridge initializes any registered RCTBridgeModules automatically, however you may wish to instantiate your own module instances (so you may inject dependencies, for example).

You can do this by creating a class that implements the RCTBridgeDelegate Protocol, initializing an RCTBridge with the delegate as an argument and initialising a RCTRootView with the initialized bridge.

id<RCTBridgeDelegate> moduleInitialiser = [[classThatImplementsRCTBridgeDelegate alloc] init]; + +RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:moduleInitialiser launchOptions:nil]; + +RCTRootView *rootView = [[RCTRootView alloc] + initWithBridge:bridge + moduleName:kModuleName + initialProperties:nil];

Exporting Constants #

A native module can export constants that are immediately available to JavaScript at runtime. This is useful for communicating static data that would otherwise require a round-trip through the bridge.

- (NSDictionary *)constantsToExport +{ + return @{ @"firstDayOfTheWeek": @"Monday" }; +}

JavaScript can use this value right away, synchronously:

console.log(CalendarManager.firstDayOfTheWeek);

Note that the constants are exported only at initialization time, so if you change constantsToExport values at runtime it won't affect the JavaScript environment.

Enum Constants #

Enums that are defined via NS_ENUM cannot be used as method arguments without first extending RCTConvert.

In order to export the following NS_ENUM definition:

typedef NS_ENUM(NSInteger, UIStatusBarAnimation) { + UIStatusBarAnimationNone, + UIStatusBarAnimationFade, + UIStatusBarAnimationSlide, +};

You must create a class extension of RCTConvert like so:

@implementation RCTConvert (StatusBarAnimation) + RCT_ENUM_CONVERTER(UIStatusBarAnimation, (@{ @"statusBarAnimationNone" : @(UIStatusBarAnimationNone), + @"statusBarAnimationFade" : @(UIStatusBarAnimationFade), + @"statusBarAnimationSlide" : @(UIStatusBarAnimationSlide)}), + UIStatusBarAnimationNone, integerValue) +@end

You can then define methods and export your enum constants like this:

- (NSDictionary *)constantsToExport +{ + return @{ @"statusBarAnimationNone" : @(UIStatusBarAnimationNone), + @"statusBarAnimationFade" : @(UIStatusBarAnimationFade), + @"statusBarAnimationSlide" : @(UIStatusBarAnimationSlide) }; +}; + +RCT_EXPORT_METHOD(updateStatusBarAnimation:(UIStatusBarAnimation)animation + completion:(RCTResponseSenderBlock)callback)

Your enum will then be automatically unwrapped using the selector provided (integerValue in the above example) before being passed to your exported method.

Sending Events to JavaScript #

The native module can signal events to JavaScript without being invoked directly. The preferred way to do this is to subclass RCTEventEmitter, implement suppportEvents and call self sendEventWithName:

// CalendarManager.h +#import <React/RCTBridgeModule.h> +#import <React/RCTEventEmitter.h> + +@interface CalendarManager : RCTEventEmitter <RCTBridgeModule> + +@end
// CalendarManager.m +#import "CalendarManager.h" + +@implementation CalendarManager + +RCT_EXPORT_MODULE(); + +- (NSArray<NSString *> *)supportedEvents +{ + return @[@"EventReminder"]; +} + +- (void)calendarEventReminderReceived:(NSNotification *)notification +{ + NSString *eventName = notification.userInfo[@"name"]; + [self sendEventWithName:@"EventReminder" body:@{@"name": eventName}]; +} + +@end

JavaScript code can subscribe to these events by creating a new NativeEventEmitter instance around your module.

import { NativeEventEmitter, NativeModules } from 'react-native'; +const { CalendarManager } = NativeModules; + +const calendarManagerEmitter = new NativeEventEmitter(CalendarManager); + +const subscription = calendarManagerEmitter.addListener( + 'EventReminder', + (reminder) => console.log(reminder.name) +); +... +// Don't forget to unsubscribe, typically in componentWillUnmount +subscription.remove();

For more examples of sending events to JavaScript, see RCTLocationObserver.

Optimizing for zero listeners #

You will receive a warning if you expend resources unnecessarily by emitting an event while there are no listeners. To avoid this, and to optimize your module's workload (e.g. by unsubscribing from upstream notifications or pausing background tasks), you can override startObserving and stopObserving in your RCTEventEmitter subclass.

@implementation CalendarManager +{ + bool hasListeners; +} + +// Will be called when this module's first listener is added. +-(void)startObserving { + hasListeners = YES; + // Set up any upstream listeners or background tasks as necessary +} + +// Will be called when this module's last listener is removed, or on dealloc. +-(void)stopObserving { + hasListeners = NO; + // Remove upstream listeners, stop unnecessary background tasks +} + +- (void)calendarEventReminderReceived:(NSNotification *)notification +{ + NSString *eventName = notification.userInfo[@"name"]; + if (hasListeners) { // Only send events if anyone is listening + [self sendEventWithName:@"EventReminder" body:@{@"name": eventName}]; + } +}

Exporting Swift #

Swift doesn't have support for macros so exposing it to React Native requires a bit more setup but works relatively the same.

Let's say we have the same CalendarManager but as a Swift class:

// CalendarManager.swift + +@objc(CalendarManager) +class CalendarManager: NSObject { + + @objc(addEvent:location:date:) + func addEvent(name: String, location: String, date: NSNumber) -> Void { + // Date is ready to use! + } + +}

NOTE: It is important to use the @objc modifiers to ensure the class and functions are exported properly to the Objective-C runtime.

Then create a private implementation file that will register the required information with the React Native bridge:

// CalendarManagerBridge.m +#import <React/RCTBridgeModule.h> + +@interface RCT_EXTERN_MODULE(CalendarManager, NSObject) + +RCT_EXTERN_METHOD(addEvent:(NSString *)name location:(NSString *)location date:(nonnull NSNumber *)date) + +@end

For those of you new to Swift and Objective-C, whenever you mix the two languages in an iOS project, you will also need an additional bridging file, known as a bridging header, to expose the Objective-C files to Swift. Xcode will offer to create this header file for you if you add your Swift file to your app through the Xcode File>New File menu option. You will need to import RCTBridgeModule.h in this header file.

// CalendarManager-Bridging-Header.h +#import <React/RCTBridgeModule.h>

You can also use RCT_EXTERN_REMAP_MODULE and RCT_EXTERN_REMAP_METHOD to alter the JavaScript name of the module or methods you are exporting. For more information see RCTBridgeModule.

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

\ No newline at end of file diff --git a/releases/0.47/docs/nativemethodsmixin.html b/releases/0.47/docs/nativemethodsmixin.html new file mode 100644 index 00000000000..09a2266ca86 --- /dev/null +++ b/releases/0.47/docs/nativemethodsmixin.html @@ -0,0 +1 @@ +Redirecting...

Redirecting...

Click here if you are not redirected. \ No newline at end of file diff --git a/releases/0.47/docs/navigation.html b/releases/0.47/docs/navigation.html new file mode 100644 index 00000000000..72c3e54ba48 --- /dev/null +++ b/releases/0.47/docs/navigation.html @@ -0,0 +1,94 @@ +Navigating Between Screens

Navigating Between Screens #

Mobile apps are rarely made up of a single screen. Managing the presentation of, and transition between, multiple screens is typically handled by what is known as a navigator.

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({ + 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', + }; + render() { + const { navigate } = this.props.navigation; + return ( + <Button + title="Go to Jane's profile" + onPress={() => + 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 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 from 'react'; +import PropTypes from 'prop-types'; +import { Button, NavigatorIOS, Text, View } from 'react-native'; + +export default class NavigatorIOSApp extends React.Component { + render() { + return ( + <NavigatorIOS + initialRoute={{ + component: MyScene, + title: 'My Initial Scene', + }} + style={{flex: 1}} + /> + ) + } +} + +class MyScene extends React.Component { + static propTypes = { + title: PropTypes.string.isRequired, + navigator: PropTypes.object.isRequired, + } + + constructor(props, context) { + super(props, context); + this._onForward = this._onForward.bind(this); + } + + _onForward() { + this.props.navigator.push({ + title: 'Scene ' + nextIndex, + }); + } + + render() { + return ( + <View> + <Text>Current Scene: { this.props.title }</Text> + <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 can edit the content above on GitHub and send us a pull request!

\ No newline at end of file diff --git a/releases/0.47/docs/navigatorios.html b/releases/0.47/docs/navigatorios.html new file mode 100644 index 00000000000..1a7e7768102 --- /dev/null +++ b/releases/0.47/docs/navigatorios.html @@ -0,0 +1,291 @@ +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 +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 +object. A route object is used to describe each scene that your app +navigates to. initialRoute represents the first route in your navigator.

import React, { Component, PropTypes } from 'react'; +import { NavigatorIOS, Text } from 'react-native'; + +export default class NavigatorIOSApp extends Component { + render() { + return ( + <NavigatorIOS + initialRoute={{ + component: MyScene, + title: 'My Initial Scene', + }} + style={{flex: 1}} + /> + ); + } +} + +class MyScene extends Component { + static propTypes = { + title: PropTypes.string.isRequired, + navigator: PropTypes.object.isRequired, + } + + _onForward = () => { + this.props.navigator.push({ + title: 'Scene ' + nextIndex, + }); + } + + render() { + return ( + <View> + <Text>Current Scene: { this.props.title }</Text> + <TouchableHighlight onPress={this._onForward}> + <Text>Tap me to load the next scene</Text> + </TouchableHighlight> + </View> + ) + } +}

In this code, the navigator renders the component specified in initialRoute, +which in this case is MyScene. This component will receive a route prop +and a navigator prop representing the navigator. The navigator's navigation +bar will render the title for the current scene, "My Initial Scene".

You can optionally pass in a passProps property to your initialRoute. +NavigatorIOS passes this in as props to the rendered component:

initialRoute={{ + component: MyScene, + title: 'My Initial Scene', + passProps: { myProp: 'foo' } +}}

You can then access the props passed in via {this.props.myProp}.

Handling Navigation #

To trigger navigation functionality such as pushing or popping a view, you +have access to a navigator object. The object is passed in as a prop to any +component that is rendered by NavigatorIOS. You can then call the +relevant methods to perform the navigation action you need:

class MyView extends Component { + _handleBackPress() { + this.props.navigator.pop(); + } + + _handleNextPress(nextRoute) { + this.props.navigator.push(nextRoute); + } + + render() { + const nextRoute = { + component: MyView, + title: 'Bar That', + passProps: { myProp: 'bar' } + }; + return( + <TouchableHighlight onPress={() => this._handleNextPress(nextRoute)}> + <Text style={{marginTop: 200, alignSelf: 'center'}}> + See you on the other nav {this.props.myProp}! + </Text> + </TouchableHighlight> + ); + } +}

You can also trigger navigator functionality from the NavigatorIOS +component:

class NavvyIOS extends Component { + _handleNavigationRequest() { + this.refs.nav.push({ + component: MyView, + title: 'Genius', + passProps: { myProp: 'genius' }, + }); + } + + render() { + return ( + <NavigatorIOS + ref='nav' + initialRoute={{ + component: MyView, + title: 'Foo This', + passProps: { myProp: 'foo' }, + rightButtonTitle: 'Add', + onRightButtonPress: () => this._handleNavigationRequest(), + }} + style={{flex: 1}} + /> + ); + } +}

The code above adds a _handleNavigationRequest private method that is +invoked from the NavigatorIOS component when the right navigation bar item +is pressed. To get access to the navigator functionality, a reference to it +is saved in the ref prop and later referenced to push a new scene into the +navigation stack.

Navigation Bar Configuration #

Props passed to NavigatorIOS will set the default configuration +for the navigation bar. Props passed as properties to a route object will set +the configuration for that route's navigation bar, overriding any props +passed to the NavigatorIOS component.

_handleNavigationRequest() { + this.refs.nav.push({ + //... + passProps: { myProp: 'genius' }, + barTintColor: '#996699', + }); +} + +render() { + return ( + <NavigatorIOS + //... + style={{flex: 1}} + barTintColor='#ffffcc' + /> + ); +}

In the example above the navigation bar color is changed when the new route +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, + + /** + * Boolean 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?: 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?: 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!

\ No newline at end of file diff --git a/releases/0.47/docs/netinfo.html b/releases/0.47/docs/netinfo.html new file mode 100644 index 00000000000..a93264b41da --- /dev/null +++ b/releases/0.47/docs/netinfo.html @@ -0,0 +1,61 @@ +NetInfo

NetInfo #

NetInfo exposes info about online/offline status

NetInfo.fetch().then((reach) => { + console.log('Initial: ' + reach); +}); +function handleFirstConnectivityChange(reach) { + console.log('First change: ' + reach); + NetInfo.removeEventListener( + 'change', + handleFirstConnectivityChange + ); +} +NetInfo.addEventListener( + 'change', + handleFirstConnectivityChange +);

IOS #

Asynchronously determine if the device is online and on a cellular network.

  • none - device is offline
  • wifi - device is online and connected via wifi, or is the iOS simulator
  • cell - device is connected via Edge, 3G, WiMax, or LTE
  • unknown - error case and the network status is unknown

Android #

To request network info, you need to add the following line to your +app's AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> +Asynchronously determine if the device is connected and details about that connection.

Android Connectivity Types.

  • NONE - device is offline
  • BLUETOOTH - The Bluetooth data connection.
  • DUMMY - Dummy data connection.
  • ETHERNET - The Ethernet data connection.
  • MOBILE - The Mobile data connection.
  • MOBILE_DUN - A DUN-specific Mobile data connection.
  • MOBILE_HIPRI - A High Priority Mobile data connection.
  • MOBILE_MMS - An MMS-specific Mobile data connection.
  • MOBILE_SUPL - A SUPL-specific Mobile data connection.
  • VPN - A virtual network using one or more native bearers. Requires API Level 21
  • WIFI - The WIFI data connection.
  • WIMAX - The WiMAX data connection.
  • UNKNOWN - Unknown data connection.

The rest ConnectivityStates are hidden by the Android API, but can be used if necessary.

isConnectionExpensive #

Available on Android. Detect if the current active connection is metered or not. A network is +classified as metered when the user is sensitive to heavy data usage on that connection due to +monetary costs, data limitations or battery/performance issues.

NetInfo.isConnectionExpensive() +.then(isConnectionExpensive => { + console.log('Connection is ' + (isConnectionExpensive ? 'Expensive' : 'Not Expensive')); +}) +.catch(error => { + console.error(error); +});

isConnected #

Available on all platforms. Asynchronously fetch a boolean to determine +internet connectivity.

NetInfo.isConnected.fetch().then(isConnected => { + console.log('First, is ' + (isConnected ? 'online' : 'offline')); +}); +function handleFirstConnectivityChange(isConnected) { + console.log('Then, is ' + (isConnected ? 'online' : 'offline')); + NetInfo.isConnected.removeEventListener( + 'change', + handleFirstConnectivityChange + ); +} +NetInfo.isConnected.addEventListener( + 'change', + handleFirstConnectivityChange +);

Methods #

static addEventListener(eventName, handler) #

Invokes the listener whenever network status changes. +The listener receives one of the connectivity types listed above.

static removeEventListener(eventName, handler) #

Removes the listener for network status changes.

static fetch() #

Returns a promise that resolves with 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!

\ No newline at end of file diff --git a/releases/0.47/docs/network.html b/releases/0.47/docs/network.html new file mode 100644 index 00000000000..bf876c8f161 --- /dev/null +++ b/releases/0.47/docs/network.html @@ -0,0 +1,126 @@ +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', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + firstParam: 'yourValue', + secondParam: 'yourOtherValue', + }) +})

Take a look at the Fetch Request docs for a full list of properties.

Handling the response #

The above examples show how you can make a request. In many cases, you will want to do something with the response.

Networking is an inherently asynchronous operation. Fetch methods will return a Promise that makes it straightforward to write code that works in an asynchronous manner:

function getMoviesFromApiAsync() { + return fetch('https://facebook.github.io/react-native/movies.json') + .then((response) => response.json()) + .then((responseJson) => { + return responseJson.movies; + }) + .catch((error) => { + console.error(error); + }); + }

You can also use the proposed ES2017 async/await syntax in a React Native app:

async function getMoviesFromApi() { + try { + let response = await fetch('https://facebook.github.io/react-native/movies.json'); + let responseJson = await response.json(); + return responseJson.movies; + } 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(); +request.onreadystatechange = (e) => { + if (request.readyState !== 4) { + return; + } + + if (request.status === 200) { + console.log('success', request.responseText); + } else { + console.warn('error'); + } +}; + +request.open('GET', 'https://mywebsite.com/endpoint/'); +request.send();

The security model for XMLHttpRequest is different than on web as there is no concept of CORS in native apps.

WebSocket Support #

React Native also supports WebSockets, a protocol which provides full-duplex communication channels over a single TCP connection.

var ws = new WebSocket('ws://host.com/path'); + +ws.onopen = () => { + // connection opened + ws.send('something'); // send a message +}; + +ws.onmessage = (e) => { + // a message was received + console.log(e.data); +}; + +ws.onerror = (e) => { + // an error occurred + console.log(e.message); +}; + +ws.onclose = (e) => { + // connection closed + console.log(e.code, e.reason); +};

High Five! #

If you've gotten here by reading linearly through the tutorial, then you are a pretty impressive human being. Congratulations. Next, you might want to check out all the cool stuff the community does with React Native.

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

\ No newline at end of file diff --git a/releases/0.47/docs/panresponder.html b/releases/0.47/docs/panresponder.html new file mode 100644 index 00000000000..11c9c8a9372 --- /dev/null +++ b/releases/0.47/docs/panresponder.html @@ -0,0 +1,79 @@ +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 +gesture responder system. +For each handler, it provides a new gestureState object alongside the +native event object:

onPanResponderMove: (event, gestureState) => {}

A native event 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

A gestureState object has the following:

  • stateID - ID of the gestureState- persisted as long as there at least + one touch on screen
  • moveX - the latest screen coordinates of the recently-moved touch
  • moveY - the latest screen coordinates of the recently-moved touch
  • x0 - the screen coordinates of the responder grant
  • y0 - the screen coordinates of the responder grant
  • dx - accumulated distance of the gesture since the touch started
  • dy - accumulated distance of the gesture since the touch started
  • vx - current velocity of the gesture
  • vy - current velocity of the gesture
  • numberActiveTouches - Number of touches currently on screen

Basic Usage #

componentWillMount: function() { + this._panResponder = PanResponder.create({ + // Ask to be the responder: + onStartShouldSetPanResponder: (evt, gestureState) => true, + onStartShouldSetPanResponderCapture: (evt, gestureState) => true, + onMoveShouldSetPanResponder: (evt, gestureState) => true, + onMoveShouldSetPanResponderCapture: (evt, gestureState) => true, + + onPanResponderGrant: (evt, gestureState) => { + // The gesture has started. Show visual feedback so the user knows + // what is happening! + + // gestureState.d{x,y} will be set to zero now + }, + onPanResponderMove: (evt, gestureState) => { + // The most recent move distance is gestureState.move{X,Y} + + // The accumulated gesture distance since becoming responder is + // gestureState.d{x,y} + }, + onPanResponderTerminationRequest: (evt, gestureState) => true, + onPanResponderRelease: (evt, gestureState) => { + // The user has released all touches while this view is the + // responder. This typically means a gesture has succeeded + }, + onPanResponderTerminate: (evt, gestureState) => { + // Another component has become the responder, so this gesture + // should be cancelled + }, + onShouldBlockNativeResponder: (evt, gestureState) => { + // Returns whether this component should block native components from becoming the JS + // responder. Returns true by default. Is currently only supported on android. + return true; + }, + }); + }, + + render: function() { + return ( + <View {...this._panResponder.panHandlers} /> + ); + },

Working Example #

To see it in action, try the +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 +example, the config object would look like:

  • onMoveShouldSetPanResponder: (e, gestureState) => {...}
  • onMoveShouldSetPanResponderCapture: (e, gestureState) => {...}
  • onStartShouldSetPanResponder: (e, gestureState) => {...}
  • onStartShouldSetPanResponderCapture: (e, gestureState) => {...}
  • onPanResponderReject: (e, gestureState) => {...}
  • onPanResponderGrant: (e, gestureState) => {...}
  • onPanResponderStart: (e, gestureState) => {...}
  • onPanResponderEnd: (e, gestureState) => {...}
  • onPanResponderRelease: (e, gestureState) => {...}
  • onPanResponderMove: (e, gestureState) => {...}
  • onPanResponderTerminate: (e, gestureState) => {...}
  • onPanResponderTerminationRequest: (e, gestureState) => {...}
  • onShouldBlockNativeResponder: (e, gestureState) => {...}

    In general, for events that have capture equivalents, we update the +gestureState once in the capture phase and can use it in the bubble phase +as well.

    Be careful with onStartShould* callbacks. They only reflect updated +gestureState for start/end events that bubble/capture to the Node. +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!

\ No newline at end of file diff --git a/releases/0.47/docs/performance.html b/releases/0.47/docs/performance.html new file mode 100644 index 00000000000..5416e4b41c2 --- /dev/null +++ b/releases/0.47/docs/performance.html @@ -0,0 +1,126 @@ +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. +We try our best to deliver buttery-smooth UI performance by default, but sometimes that just isn't possible.

This guide is intended to teach you some basics to help you to troubleshoot performance issues, +as well as discuss common sources of problems and their suggested solutions.

What you need to know about frames #

Your grandparents' generation called movies "moving pictures" for a reason: +realistic motion in video is an illusion created by quickly changing static images at a consistent speed. We refer to each of these images as frames. +The number of frames that is displayed each second has a direct impact on how smooth and ultimately life-like a video (or user interface) seems to be. +iOS devices display 60 frames per second, which gives you and the UI system about 16.67ms to do all of the work needed to generate the static image (frame) that the user will see on the screen for that interval. +If you are unable to do the work necessary to generate that frame within the allotted 16.67ms, then you will "drop a frame" and the UI will appear unresponsive.

Now to confuse the matter a little bit, open up the developer menu in your app and toggle Show Perf Monitor. +You will notice that there are two different frame rates.

JS frame rate (JavaScript thread) #

For most React Native applications, your business logic will run on the JavaScript thread. +This is where your React application lives, API calls are made, touch events are processed, etc... +Updates to native-backed views are batched and sent over to the native side at the end of each iteration of the event loop, +before the frame deadline (if all goes well). +If the JavaScript thread is unresponsive for a frame, it will be considered a dropped frame. +For example, if you were to call this.setState on the root component of a complex application and it resulted in re-rendering computationally expensive component subtrees, +it's conceivable that this might take 200ms and result in 12 frames being dropped. +Any animations controlled by JavaScript would appear to freeze during that time. +If anything takes longer than 100ms, the user will feel it.

This often happens during Navigator transitions: +when you push a new route, the JavaScript thread needs to render all of the components necessary for the scene in order to send over the proper commands to the native side to create the backing views. +It's common for the work being done here to take a few frames and cause jank because the transition is controlled by the JavaScript thread. +Sometimes components will do additional work on componentDidMount, which might result in a second stutter in the transition.

Another example is responding to touches: +if you are doing work across multiple frames on the JavaScript thread, you might notice a delay in responding to TouchableOpacity, for example. +This is because the JavaScript thread is busy and cannot process the raw touch events sent over from the main thread. +As a result, TouchableOpacity cannot react to the touch events and command the native view to adjust its opacity.

UI frame rate (main thread) #

Many people have noticed that performance of NavigatorIOS is better out of the box than Navigator. +The reason for this is that the animations for the transitions are done entirely on the main thread, +and so they are not interrupted by frame drops on the JavaScript thread.

Similarly, you can happily scroll up and down through a ScrollView when the JavaScript thread is locked up because the ScrollView lives on the main thread. +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. +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 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. +You will find that enabling shouldRasterizeIOS or renderToHardwareTextureAndroid can help with this significantly.

Be careful not to overuse this or your memory usage could go through the roof. +Profile your performance and memory usage when using these props. +If you don't plan to move a view anymore, turn this property off.

Animating the size of an image drops UI thread FPS #

On iOS, each time you adjust the width or height of an Image component it is re-cropped and scaled from the original image. +This can be very expensive, especially for large images. +Instead, use the transform: [{scale}] style property to animate the size. +An example of when you might do this is when you tap an image and zoom it in to full screen.

My TouchableX view isn't very responsive #

Sometimes, if we do an action in the same frame that we are adjusting the opacity or highlight of a component that is responding to a touch, +we won't see that effect until after the onPress function has returned. +If onPress does a setState that results in a lot of work and a few frames dropped, this may occur. +A solution to this is to wrap any action inside of your onPress handler in requestAnimationFrame:

handleOnPress() { + // Always use TimerMixin with requestAnimationFrame, setTimeout and + // setInterval + this.requestAnimationFrame(() => { + this.doExpensiveAction(); + }); +}

Slow navigator transitions #

As mentioned above, Navigator animations are controlled by the JavaScript thread. +Imagine the "push from right" scene transition: +each frame, the new scene is moved from the right to left, +starting offscreen (let's say at an x-offset of 320) and ultimately settling when the scene sits at an x-offset of 0. +Each frame during this transition, the JavaScript thread needs to send a new x-offset to the main thread. +If the JavaScript thread is locked up, it cannot do this and so no update occurs on that frame and the animation stutters.

One solution to this is to allow for JavaScript-based animations to be offloaded to the main thread. +If we were to do the same thing as in the above example with this approach, +we might calculate a list of all x-offsets for the new scene when we are starting the transition and send them to the main thread to execute in an optimized way. +Now that the JavaScript thread is freed of this responsibility, +it's not a big deal if it drops a few frames while rendering the scene -- you probably won't even notice because you will be too distracted by the pretty transition.

Solving this is one of the main goals behind the new React Navigation library. +The views in React Navigation use native components and the Animated library to deliver 60 FPS animations that are run on the native thread.

Profiling #

Use the built-in profiler to get detailed information about work done in the JavaScript thread and main thread side-by-side. +Access it by selecting Perf Monitor from the Debug menu.

For iOS, Instruments is an invaluable tool, and on Android you should learn to use systrace.

You can also use react-addons-perf to get insights into where React is spending time when rendering your components.

Another way to profile JavaScript is to use the Chrome profiler while debugging. +This won't give you accurate results as the code is running in Chrome but will give you a general idea of where bottlenecks might be.

But first, make sure that Development Mode is OFF! You should see __DEV__ === false, development-level warning are OFF, performance optimizations are ON in your application logs.

Profiling Android UI Performance with systrace #

Android supports 10k+ different phones and is generalized to support software rendering: +the framework architecture and need to generalize across many hardware targets unfortunately means you get less for free relative to iOS. +But sometimes, there are things you can improve -- and many times it's not native code's fault at all!

The first step for debugging this jank is to answer the fundamental question of where your time is being spent during each 16ms frame. +For that, we'll be using a standard Android profiling tool called systrace.

systrace is a standard Android marker-based profiling tool (and is installed when you install the Android platform-tools package). +Profiled code blocks are surrounded by start/end markers which are then visualized in a colorful chart format. +Both the Android SDK and React Native framework provide standard markers that you can visualize.

1. Collecting a trace #

First, connect a device that exhibits the stuttering you want to investigate to your computer via USB and get it to the point right before the navigation/animation you want to profile. +Run systrace as follows:

$ <path_to_android_sdk>/platform-tools/systrace/systrace.py --time=10 -o trace.html sched gfx view -a <your_package_name>

A quick breakdown of this command:

  • time is the length of time the trace will be collected in seconds
  • sched, gfx, and view are the android SDK tags (collections of markers) we care about: sched gives you information about what's running on each core of your phone, gfx gives you graphics info such as frame boundaries, and view gives you information about measure, layout, and draw passes
  • -a <your_package_name> enables app-specific markers, specifically the ones built into the React Native framework. your_package_name can be found in the AndroidManifest.xml of your app and looks like com.example.app

Once the trace starts collecting, perform the animation or interaction you care about. At the end of the trace, systrace will give you a link to the trace which you can open in your browser.

2. Reading the trace #

After opening the trace in your browser (preferably Chrome), you should see something like this:

Example

HINT: +Use the WASD keys to strafe and zoom

If your trace .html file isn't opening correctly, check your browser console for the following:

ObjectObserveError

Since Object.observe was deprecated in recent browsers, you may have to open the file from the Google Chrome Tracing tool. You can do so by:

  • Opening tab in chrome chrome://tracing
  • Selecting load
  • Selecting the html file generated from the previous command.

Enable VSync highlighting

Check this checkbox at the top right of the screen to highlight the 16ms frame boundaries:

Enable VSync Highlighting

You should see zebra stripes as in the screenshot above. +If you don't, try profiling on a different device: Samsung has been known to have issues displaying vsyncs while the Nexus series is generally pretty reliable.

3. Find your process #

Scroll until you see (part of) the name of your package. +In this case, I was profiling com.facebook.adsmanager, +which shows up as book.adsmanager because of silly thread name limits in the kernel.

On the left side, you'll see a set of threads which correspond to the timeline rows on the right. +There are a few threads we care about for our purposes: +the UI thread (which has your package name or the name UI Thread), mqt_js, and mqt_native_modules. +If you're running on Android 5+, we also care about the Render Thread.

  • UI Thread. +This is where standard android measure/layout/draw happens. +The thread name on the right will be your package name (in my case book.adsmanager) or UI Thread. +The events that you see on this thread should look something like this and have to do with Choreographer, traversals, and DispatchUI:

    UI Thread Example

  • JS Thread. +This is where JavaScript is executed. +The thread name will be either mqt_js or <...> depending on how cooperative the kernel on your device is being. +To identify it if it doesn't have a name, look for things like JSCall, Bridge.executeJSCall, etc:

    JS Thread Example

  • Native Modules Thread. +This is where native module calls (e.g. the UIManager) are executed. +The thread name will be either mqt_native_modules or <...>. +To identify it in the latter case, look for things like NativeCall, callJavaModuleMethod, and onBatchComplete:

    Native Modules Thread Example

  • Bonus: Render Thread. +If you're using Android L (5.0) and up, you will also have a render thread in your application. +This thread generates the actual OpenGL commands used to draw your UI. +The thread name will be either RenderThread or <...>. +To identify it in the latter case, look for things like DrawFrame and queueBuffer:

    Render Thread Example

Identifying a culprit #

A smooth animation should look something like the following:

Smooth Animation

Each change in color is a frame -- remember that in order to display a frame, +all our UI work needs to be done by the end of that 16ms period. +Notice that no thread is working close to the frame boundary. +An application rendering like this is rendering at 60 FPS.

If you noticed chop, however, you might see something like this:

Choppy Animation from JS

Notice that the JS thread is executing basically all the time, and across frame boundaries! +This app is not rendering at 60 FPS. +In this case, the problem lies in JS.

You might also see something like this:

Choppy Animation from UI

In this case, the UI and render threads are the ones that have work crossing frame boundaries. +The UI that we're trying to render on each frame is requiring too much work to be done. +In this case, the problem lies in the native views being rendered.

At this point, you'll have some very helpful information to inform your next steps.

Resolving JavaScript issues #

If you identified a JS problem, +look for clues in the specific JS that you're executing. +In the scenario above, we see RCTEventEmitter being called multiple times per frame. +Here's a zoom-in of the JS thread from the trace above:

Too much JS

This doesn't seem right. +Why is it being called so often? +Are they actually different events? +The answers to these questions will probably depend on your product code. +And many times, you'll want to look into shouldComponentUpdate.

Resolving native UI Issues #

If you identified a native UI problem, there are usually two scenarios:

  1. the UI you're trying to draw each frame involves too much work on the GPU, or
  2. You're constructing new UI during the animation/interaction (e.g. loading in new content during a scroll).
Too much GPU work #

In the first scenario, you'll see a trace that has the UI thread and/or Render Thread looking like this:

Overloaded GPU

Notice the long amount of time spent in DrawFrame that crosses frame boundaries. This is time spent waiting for the GPU to drain its command buffer from the previous frame.

To mitigate this, you should:

  • investigate using renderToHardwareTextureAndroid for complex, static content that is being animated/transformed (e.g. the Navigator slide/alpha animations)
  • make sure that you are not using needsOffscreenAlphaCompositing, which is disabled by default, as it greatly increases the per-frame load on the GPU in most cases.

If these don't help and you want to dig deeper into what the GPU is actually doing, you can check out Tracer for OpenGL ES.

Creating new views on the UI thread #

In the second scenario, you'll see something more like this:

Creating Views

Notice that first the JS thread thinks for a bit, then you see some work done on the native modules thread, followed by an expensive traversal on the UI thread.

There isn't an easy way to mitigate this unless you're able to postpone creating new UI until after the interaction, or you are able to simplify the UI you're creating. The react native team is working on a infrastructure level solution for this that will allow new UI to be created and configured off the main thread, allowing the interaction to continue smoothly.

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

\ No newline at end of file diff --git a/releases/0.47/docs/permissionsandroid.html b/releases/0.47/docs/permissionsandroid.html new file mode 100644 index 00000000000..943e3c00d03 --- /dev/null +++ b/releases/0.47/docs/permissionsandroid.html @@ -0,0 +1,71 @@ +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 +permissions.

On devices before SDK version 23, the permissions are automatically granted +if they appear in the manifest, so check and request +should always be true.

If a user has previously turned off a permission that you prompt for, the OS +will advise your app to show a rationale for needing the permission. The +optional rationale argument will show a dialog prompt only if +necessary - otherwise the normal permission prompt will appear.

Example #

async function requestCameraPermission() { + try { + const granted = await PermissionsAndroid.request( + PermissionsAndroid.PERMISSIONS.CAMERA, + { + 'title': 'Cool Photo App Camera Permission', + 'message': 'Cool Photo App needs access to your camera ' + + 'so you can take awesome pictures.' + } + ) + if (granted === PermissionsAndroid.RESULTS.GRANTED) { + console.log("You can use the camera") + } else { + console.log("Camera permission denied") + } + } catch (err) { + console.warn(err) + } +}

Methods #

constructor() #

checkPermission(permission) #

DEPRECATED - use check

Returns a promise resolving to a boolean value as to whether the specified +permissions has been granted

@deprecated

check(permission) #

Returns a promise resolving to a boolean value as to whether the specified +permissions has been granted

requestPermission(permission, rationale?) #

DEPRECATED - use request

Prompts the user to enable a permission and returns a promise resolving to a +boolean value indicating whether the user allowed or denied the request

If the optional rationale argument is included (which is an object with a +title and message), this function checks with the OS whether it is +necessary to show a dialog explaining why the permission is needed +(https://developer.android.com/training/permissions/requesting.html#explain) +and then shows the system permission dialog

@deprecated

request(permission, rationale?) #

Prompts the user to enable a permission and returns a promise resolving to a +string value indicating whether the user allowed or denied the request

If the optional rationale argument is included (which is an object with a +title and message), this function checks with the OS whether it is +necessary to show a dialog explaining why the permission is needed +(https://developer.android.com/training/permissions/requesting.html#explain) +and then shows the system permission dialog

requestMultiple(permissions) #

Prompts the user to enable multiple permissions in the same dialog and +returns an object with the permissions as keys and strings as values +indicating whether the user allowed or denied the request

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

\ No newline at end of file diff --git a/releases/0.47/docs/picker.html b/releases/0.47/docs/picker.html new file mode 100644 index 00000000000..80650a96715 --- /dev/null +++ b/releases/0.47/docs/picker.html @@ -0,0 +1,27 @@ +Picker

Picker #

Renders the native picker component on iOS and Android. Example:

<Picker + selectedValue={this.state.language} + 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!

\ No newline at end of file diff --git a/releases/0.47/docs/pickerios.html b/releases/0.47/docs/pickerios.html new file mode 100644 index 00000000000..ec426389428 --- /dev/null +++ b/releases/0.47/docs/pickerios.html @@ -0,0 +1,19 @@ +PickerIOS

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 diff --git a/releases/0.47/docs/pixelratio.html b/releases/0.47/docs/pixelratio.html new file mode 100644 index 00000000000..7cf4afa705a --- /dev/null +++ b/releases/0.47/docs/pixelratio.html @@ -0,0 +1,32 @@ +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), + height: PixelRatio.getPixelSizeForLayoutSize(100), +}); +<Image source={image} style={{width: 200, height: 100}} />

Methods #

static get() #

Returns the device pixel density. Some examples:

  • PixelRatio.get() === 1
    • mdpi Android devices (160 dpi)
  • PixelRatio.get() === 1.5
    • hdpi Android devices (240 dpi)
  • PixelRatio.get() === 2
    • iPhone 4, 4S
    • iPhone 5, 5c, 5s
    • iPhone 6
    • xhdpi Android devices (320 dpi)
  • PixelRatio.get() === 3
    • iPhone 6 plus
    • xxhdpi Android devices (480 dpi)
  • PixelRatio.get() === 3.5
    • Nexus 6

static getFontScale() #

Returns the scaling factor for font sizes. This is the ratio that is used to calculate the +absolute font size, so any elements that heavily depend on that should use this to do +calculations.

If a font scale is not set, this returns the device pixel ratio.

Currently this is only implemented on Android and reflects the user preference set in +Settings > Display > Font size, on iOS it will always return the default pixel ratio. +@platform android

static getPixelSizeForLayoutSize(layoutSize) #

Converts a layout size (dp) to pixel size (px).

Guaranteed to return an integer number.

static roundToNearestPixel(layoutSize) #

Rounds a layout size (dp) to the nearest layout size that corresponds to +an integer number of pixels. For example, on a device with a PixelRatio +of 3, PixelRatio.roundToNearestPixel(8.4) = 8.33, which corresponds to +exactly (8.33 * 3) = 25 pixels.

static startDetecting() #

// No-op for iOS, but used on the web. Should not be documented.

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

Description #

Pixel Grid Snapping #

In iOS, you can specify positions and dimensions for elements with arbitrary precision, for example 29.674825. But, ultimately the physical display only have a fixed number of pixels, for example 640×960 for iPhone 4 or 750×1334 for iPhone 6. iOS tries to be as faithful as possible to the user value by spreading one original pixel into multiple ones to trick the eye. The downside of this technique is that it makes the resulting element look blurry.

In practice, we found out that developers do not want this feature and they have to work around it by doing manual rounding in order to avoid having blurry elements. In React Native, we are rounding all the pixels automatically.

We have to be careful when to do this rounding. You never want to work with rounded and unrounded values at the same time as you're going to accumulate rounding errors. Having even one rounding error is deadly because a one pixel border may vanish or be twice as big.

In React Native, everything in JS and within the layout engine work with arbitrary precision numbers. It's only when we set the position and dimensions of the native element on the main thread that we round. Also, rounding is done relative to the root rather than the parent, again to avoid accumulating rounding errors.

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

\ No newline at end of file diff --git a/releases/0.47/docs/platform-specific-code.html b/releases/0.47/docs/platform-specific-code.html new file mode 100644 index 00000000000..9a8918c22c6 --- /dev/null +++ b/releases/0.47/docs/platform-specific-code.html @@ -0,0 +1,52 @@ +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, +});

Platform.OS will be ios when running on iOS and android when running on Android.

There is also a Platform.select method available, that given an object containing Platform.OS as keys, returns the value for the platform you are currently running on.

import { Platform, StyleSheet } from 'react-native'; + +const styles = StyleSheet.create({ + container: { + flex: 1, + ...Platform.select({ + ios: { + backgroundColor: 'red', + }, + android: { + backgroundColor: 'blue', + }, + }), + }, +});

This will result in a container having flex: 1 on both platforms, a red background color on iOS, and a blue background color on Android.

Since it accepts any value, you can also use it to return platform specific component, like below:

const Component = Platform.select({ + ios: () => require('ComponentIOS'), + android: () => require('ComponentAndroid'), +})(); + +<Component />;

Detecting the Android version #

On Android, the Platform module can also be used to detect the version of the Android Platform in which the app is running:

import { Platform } from 'react-native'; + +if (Platform.Version === 25) { + console.log('Running on Nougat!'); +}

Detecting the iOS version #

On iOS, the Version is a result of -[UIDevice systemVersion], which is a string with the current version of the operating system. An example of the system version is "10.3". For example, to detect the major version number on iOS:

import { Platform } from 'react-native'; + +const majorVersionIOS = parseInt(Platform.Version, 10); +if (majorVersionIOS <= 9) { + console.log('Work around a change in behavior'); +}

Platform-specific extensions #

When your platform-specific code is more complex, you should consider splitting the code out into separate files. React Native will detect when a file has a .ios. or .android. extension and load the relevant platform file when required from other components.

For example, say you have the following files in your project:

BigButton.ios.js +BigButton.android.js

You can then require the component as follows:

const BigButton = require('./BigButton');

React Native will automatically pick up the right file based on the running platform.

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

\ No newline at end of file diff --git a/releases/0.47/docs/progressbarandroid.html b/releases/0.47/docs/progressbarandroid.html new file mode 100644 index 00000000000..19e22876524 --- /dev/null +++ b/releases/0.47/docs/progressbarandroid.html @@ -0,0 +1,34 @@ +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}> + <ProgressBar styleAttr="Inverse" /> + </View>; + + return ( + <MyLoadingComponent + componentView={componentView} + loadingView={progressBar} + style={styles.loadingComponent} + /> + ); +},

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?: PropTypes.number #

The progress value (between 0 and 1).

styleAttr?: PropTypes.oneOf(STYLE_ATTRIBUTES) #

Style of the ProgressBar. One of:

  • Horizontal
  • Normal (default)
  • Small
  • Large
  • Inverse
  • SmallInverse
  • LargeInverse

testID?: PropTypes.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!

\ No newline at end of file diff --git a/releases/0.47/docs/progressviewios.html b/releases/0.47/docs/progressviewios.html new file mode 100644 index 00000000000..46b89120e17 --- /dev/null +++ b/releases/0.47/docs/progressviewios.html @@ -0,0 +1,19 @@ +ProgressViewIOS

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 diff --git a/releases/0.47/docs/props.html b/releases/0.47/docs/props.html new file mode 100644 index 00000000000..24dbae2cef1 --- /dev/null +++ b/releases/0.47/docs/props.html @@ -0,0 +1,63 @@ +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'; + +export default class Bananas extends Component { + render() { + let pic = { + uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg' + }; + return ( + <Image source={pic} style={{width: 193, height: 110}}/> + ); + } +} + +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => 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'; + +class Greeting extends Component { + render() { + return ( + <Text>Hello {this.props.name}!</Text> + ); + } +} + +export default class LotsOfGreetings extends Component { + render() { + return ( + <View style={{alignItems: 'center'}}> + <Greeting name='Rexxar' /> + <Greeting name='Jaina' /> + <Greeting name='Valeera' /> + </View> + ); + } +} + +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => 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 diff --git a/releases/0.47/docs/pushnotificationios.html b/releases/0.47/docs/pushnotificationios.html new file mode 100644 index 00000000000..b23d2b67f6b --- /dev/null +++ b/releases/0.47/docs/pushnotificationios.html @@ -0,0 +1,87 @@ +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.

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]; + } + // Required for the register event. + - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken + { + [RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; + } + // Required for the notification event. You must call the completion handler after handling the remote notification. + - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo + fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler + { + [RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]; + } + // Required for the registrationError event. + - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error + { + [RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error]; + } + // Required for the localNotification event. + - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification + { + [RCTPushNotificationManager didReceiveLocalNotification:notification]; + }

Methods #

=(NewData, NoData, ResultFailed, }, static, (, :) #

static scheduleLocalNotification(details) #

Schedules the localNotification for future presentation.

details is an object containing:

  • fireDate : The date and time when the system should deliver the notification.
  • alertBody : The message displayed in the notification alert.
  • alertAction : The "action" displayed beneath an actionable notification. Defaults to "view";
  • soundName : The sound played when the notification is fired (optional).
  • isSilent : If true, the notification will appear without sound (optional).
  • category : The category of this notification, required for actionable notifications (optional).
  • userInfo : An optional object containing additional notification data.
  • applicationIconBadgeNumber (optional) : The number to display as the app's icon badge. Setting the number to 0 removes the icon badge.
  • repeatInterval : The interval to repeat as a string. Possible values: minute, hour, day, week, month, year.

static cancelAllLocalNotifications() #

Cancels all scheduled localNotifications

static removeAllDeliveredNotifications() #

Remove all delivered notifications from Notification Center

static getDeliveredNotifications(callback) #

Provides you with a list of the app’s notifications that are still displayed in Notification Center

@param callback Function which receive an array of delivered notifications

A delivered notification is an object containing:

  • identifier : The identifier of this notification.
  • title : The title of this notification.
  • body : The body of this notification.
  • category : The category of this notification, if has one.
  • userInfo : An optional object containing additional notification data.
  • thread-id : The thread identifier of this notification, if has one.

static removeDeliveredNotifications(identifiers) #

Removes the specified notifications from Notification Center

@param identifiers Array of notification identifiers

static setApplicationIconBadgeNumber(number) #

Sets the badge number for the app icon on the home screen

static getApplicationIconBadgeNumber(callback) #

Gets the current badge number for the app icon on the home screen

static cancelLocalNotifications(userInfo) #

Cancel local notifications.

Optionally restricts the set of canceled notifications to those +notifications whose userInfo fields match the corresponding fields +in the userInfo argument.

static getScheduledLocalNotifications(callback) #

Gets the local notifications that are currently scheduled.

static addEventListener(type, handler) #

Attaches a listener to remote or local notification events while the app is running +in the foreground or the background.

Valid events are:

  • notification : Fired when a remote notification is received. The +handler will be invoked with an instance of PushNotificationIOS.
  • localNotification : Fired when a local notification is received. The +handler will be invoked with an instance of PushNotificationIOS.
  • register: Fired when the user registers for remote notifications. The +handler will be invoked with a hex string representing the deviceToken.
  • registrationError: Fired when the user fails to register for remote +notifications. Typically occurs when APNS is having issues, or the device +is a simulator. The handler will be invoked with +{message: string, code: number, details: any}.

static removeEventListener(type, handler) #

Removes the event listener. Do this in componentWillUnmount to prevent +memory leaks

static requestPermissions(permissions?) #

Requests notification permissions from iOS, prompting the user's +dialog box. By default, it will request all notification permissions, but +a subset of these can be requested by passing a map of requested +permissions. +The following permissions are supported:

  • alert
  • badge
  • sound

If a map is provided to the method, only the permissions with truthy values +will be requested.

This method returns a promise that will resolve when the user accepts, +rejects, or if the permissions were previously rejected. The promise +resolves to the current state of the permission.

static abandonPermissions() #

Unregister for all remote notifications received via Apple Push Notification service.

You should call this method in rare circumstances only, such as when a new version of +the app removes support for all types of remote notifications. Users can temporarily +prevent apps from receiving remote notifications through the Notifications section of +the Settings app. Apps unregistered through this method can always re-register.

static checkPermissions(callback) #

See what push permissions are currently enabled. callback will be +invoked with a permissions object:

  • alert :boolean
  • badge :boolean
  • sound :boolean

static getInitialNotification() #

This method returns a promise that resolves to either the notification +object if the app was launched by a push notification, or null otherwise.

constructor(nativeNotif) #

You will never need to instantiate PushNotificationIOS yourself. +Listening to the notification event and invoking +getInitialNotification is sufficient

finish(fetchResult) #

This method is available for remote notifications that have been received via: +application:didReceiveRemoteNotification:fetchCompletionHandler: +https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/#//apple_ref/occ/intfm/UIApplicationDelegate/application:didReceiveRemoteNotification:fetchCompletionHandler:

Call this to execute when the remote notification handling is complete. When +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

getCategory() #

Gets the category string from the aps object

getAlert() #

Gets the notification's main message from the aps object

getContentAvailable() #

Gets the content-available number 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!

\ No newline at end of file diff --git a/releases/0.47/docs/refreshcontrol.html b/releases/0.47/docs/refreshcontrol.html new file mode 100644 index 00000000000..775c190f84c --- /dev/null +++ b/releases/0.47/docs/refreshcontrol.html @@ -0,0 +1,53 @@ +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) { + super(props); + this.state = { + refreshing: false, + }; + } + + _onRefresh() { + this.setState({refreshing: true}); + fetchData().then(() => { + this.setState({refreshing: false}); + }); + } + + render() { + return ( + <ListView + refreshControl={ + <RefreshControl + refreshing={this.state.refreshing} + onRefresh={this._onRefresh.bind(this)} + /> + } + ... + > + ... + </ListView> + ); + } + ... +}

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?: PropTypes.func #

Called when the view starts refreshing.

refreshing?: PropTypes.bool.isRequired #

Whether the view should be indicating an active refresh.

androidcolors?: PropTypes.arrayOf(ColorPropType) #

The colors (at least one) that will be used to draw the refresh indicator.

androidenabled?: PropTypes.bool #

Whether the pull to refresh functionality is enabled.

androidprogressBackgroundColor?: color #

The background color of the refresh indicator.

androidprogressViewOffset?: PropTypes.number #

Progress view top offset

androidsize?: PropTypes.oneOf([RefreshLayoutConsts.SIZE.DEFAULT, RefreshLayoutConsts.SIZE.LARGE]) #

Size of the refresh indicator, see RefreshControl.SIZE.

iostintColor?: color #

The color of the refresh indicator.

iostitle?: PropTypes.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!

\ No newline at end of file diff --git a/releases/0.47/docs/running-on-device-android.html b/releases/0.47/docs/running-on-device-android.html new file mode 100644 index 00000000000..d8ca0f0d6f1 --- /dev/null +++ b/releases/0.47/docs/running-on-device-android.html @@ -0,0 +1 @@ +Redirecting...

Redirecting...

Click here if you are not redirected. \ No newline at end of file diff --git a/releases/0.47/docs/running-on-device-ios.html b/releases/0.47/docs/running-on-device-ios.html new file mode 100644 index 00000000000..d8ca0f0d6f1 --- /dev/null +++ b/releases/0.47/docs/running-on-device-ios.html @@ -0,0 +1 @@ +Redirecting...

Redirecting...

Click here if you are not redirected. \ No newline at end of file diff --git a/releases/0.47/docs/running-on-device.html b/releases/0.47/docs/running-on-device.html new file mode 100644 index 00000000000..e4ce6eddbd1 --- /dev/null +++ b/releases/0.47/docs/running-on-device.html @@ -0,0 +1,168 @@ +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.

If you used Create React Native App to set up your project, you can preview your app on a device by scanning the QR code with the Expo app. In order to build and run your app on a device, you will need to eject and install the native code dependencies from the Getting Started guide.

+ +
    + + +
+
+ +
+ +

Running your app on iOS devices #

+ +

Running your app on Android devices #

+ +
+Development OS: +macOS +Linux +Windows +
+ +
+ +

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.

+ +

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 #

Register for an Apple developer account if you don't have one yet.

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.

+ +

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.

+ +

Next, check the manufacturer code by using lsusb (on mac, you must first install lsusb). lsusb should output something like this:

$ lsusb +Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub +Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub +Bus 001 Device 003: ID 22b8:2e76 Motorola PCS +Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub +Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub +Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub +Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

These lines represent the USB devices currently connected to your machine.

You want the line that represents your phone. If you're in doubt, try unplugging your phone and running the command again:

$ lsusb +Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub +Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub +Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub +Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub +Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub +Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

You'll see that after removing the phone, the line which has the phone model ("Motorola PCS" in this case) disappeared from the list. This is the line that we care about.

Bus 001 Device 003: ID 22b8:2e76 Motorola PCS

From the above line, you want to grab the first four digits from the device ID:

22b8:2e76

In this case, it's 22b8. That's the identifier for Motorola.

You'll need to input this into your udev rules in order to get up and running:

echo SUBSYSTEM=="usb", ATTR{idVendor}=="22b8", MODE="0666", GROUP="plugdev" | sudo tee /etc/udev/rules.d/51-android-usb.rules

Make sure that you replace 22b8 with the identifier you get in the above command.

+ +

Now check that your device is properly connecting to ADB, the Android Debug Bridge, by running adb devices.

$ adb devices +List of devices attached +emulator-5554 offline # Google emulator +14ed2fcc device # Physical device

Seeing device in the right column means the device is connected. You must have only one device connected at a time.

3. Run your app #

Type the following in your command prompt to install and launch your app on the device:

$ react-native run-android

If you get a "bridge configuration isn't available" error, see Using adb reverse.

Hint

You can also use the React Native CLI to generate and run a Release build (e.g. react-native run-android --variant=release).

+ + + +

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) 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.

+ +

You can find the IP address in System PreferencesNetwork.

+ +

Open the command prompt and type ipconfig to find your machine's IP address (more info).

+ +

Open a terminal and type /sbin/ifconfig to find your machine's IP address.

+ +
  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.

1. Enable App Transport Security #

App Transport Security is a security feature introduced 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 for localhost by default in React Native projects in order to make development easier.

You should re-enable ATS prior to building your app for production by removing the localhost entry from the NSExceptionDomains dictionary in your Info.plist file in the ios/ folder. You can also re-enable ATS from within Xcode by opening your target properties under the Info pane and editing the App Transport Security Settings entry.

If your application needs to access HTTP resources on production, see this post to learn how to configure ATS on your project.

2. Configure release scheme #

Building an app for distribution in the App Store requires using the Release scheme in Xcode. 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 bundle the JavaScript locally, so you can put the app on a device and test whilst not connected to the computer.

To configure your app to be built using the Release scheme, go to ProductSchemeEdit Scheme. Select the Run tab in the sidebar, then set the Build Configuration dropdown to Release.

3. Build app for release #

You can now build your app for release by tapping ⌘B or selecting ProductBuild from the menu bar. Once built for release, you'll be able to distribute the app to beta testers and submit the app to the App Store.

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).

+ +

Building your app for production #

You have built a great app using React Native, and you are now itching to release it in the Play Store. The process is the same as any other native Android app, with some additional considerations to take into account. Follow the guide for generating a signed APK to learn more.

+

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

\ No newline at end of file diff --git a/releases/0.47/docs/running-on-simulator-ios.html b/releases/0.47/docs/running-on-simulator-ios.html new file mode 100644 index 00000000000..9b14d00ffd4 --- /dev/null +++ b/releases/0.47/docs/running-on-simulator-ios.html @@ -0,0 +1,19 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/scrollview.html b/releases/0.47/docs/scrollview.html new file mode 100644 index 00000000000..5db71aee480 --- /dev/null +++ b/releases/0.47/docs/scrollview.html @@ -0,0 +1,145 @@ +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 +set the height of the view directly (discouraged) or make sure all parent +views have bounded height. Forgetting to transfer {flex: 1} down the +view stack can lead to errors here, which the element inspector makes +easy to debug.

Doesn't yet support other contained responders from blocking this scroll +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 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 +screen to save memory and processing time.

FlatList is also handy if you want to render separators between your items, +multiple columns, infinite scroll loading, or any number of other features it +supports out of the box.

Props #

contentContainerStyle?: StyleSheetPropType(ViewStylePropTypes) #

These styles will be applied to the scroll view content container which +wraps all of the child views. Example:

return ( + <ScrollView contentContainerStyle={styles.contentContainer}> + </ScrollView> +); +... +const styles = StyleSheet.create({ + contentContainer: { + paddingVertical: 20 + } +});

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?: 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?: 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?: 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?: 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?: 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?: PropTypes.bool #

When false, the view cannot be scrolled via touch interaction. +The default value is true.

Note that the view can be always be scrolled by calling scrollTo.

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 +with horizontal={true}.

style?: style #

backfaceVisibility ReactPropTypes.oneOf(['visible', 'hidden'])
backgroundColor color
borderBottomColor color
borderBottomLeftRadius ReactPropTypes.number
borderBottomRightRadius ReactPropTypes.number
borderBottomWidth ReactPropTypes.number
borderColor color
borderLeftColor color
borderLeftWidth ReactPropTypes.number
borderRadius ReactPropTypes.number
borderRightColor color
borderRightWidth ReactPropTypes.number
borderStyle ReactPropTypes.oneOf(['solid', 'dotted', 'dashed'])
borderTopColor color
borderTopLeftRadius ReactPropTypes.number
borderTopRightRadius ReactPropTypes.number
borderTopWidth ReactPropTypes.number
borderWidth ReactPropTypes.number
opacity ReactPropTypes.number
androidelevation ReactPropTypes.number

(Android-only) Sets the elevation of a view, using Android's underlying +elevation API. +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?: 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.

iosDEPRECATED_sendUpdatedChildFrames?: PropTypes.bool #

When true, ScrollView will emit updateChildFrames data in scroll events, +otherwise will not compute or emit child frame data. This only exists +to support legacy issues, onLayout should be used instead to retrieve +frame data. +The default value is false.

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?: 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?: 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?: 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?: 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?: 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?: 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?: 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?: 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. +You will not notice a difference between values set between 1-16 as the +JS run loop is synced to the screen refresh rate. If you do not need precise +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?: 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?: 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. Typically used in +combination with snapToAlignment and decelerationRate="fast". +Overrides less configurable pagingEnabled prop.

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.

flashScrollIndicators() #

Displays the scroll indicators momentarily.

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

\ No newline at end of file diff --git a/releases/0.47/docs/sectionlist.html b/releases/0.47/docs/sectionlist.html new file mode 100644 index 00000000000..d154a0a7502 --- /dev/null +++ b/releases/0.47/docs/sectionlist.html @@ -0,0 +1,93 @@ +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: [...], title: ...}, + {data: [...], title: ...}, + {data: [...], title: ...}, + ]} +/> + +<SectionList + sections={[ // heterogeneous rendering between sections + {data: [...], title: ..., renderItem: ...}, + {data: [...], title: ..., renderItem: ...}, + {data: [...], title: ..., renderItem: ...}, + ]} +/>

This is a convenience wrapper around <VirtualizedList>, +and thus inherits its 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 +(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 and 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. 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.

inverted?: ?boolean #

Reverses the direction of scroll. Uses scale transforms of -1.

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.

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 +within half the visible length of the list.

onRefresh?: ?() => void #

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 #

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: Item, + index: number, + section: SectionT, + separators: { + highlight: () => void, + unhighlight: () => void, + updateProps: (select: 'leading' | 'trailing', newProps: Object) => void, + }, +}) => ?React.Element<any> #

Default renderer for every item in every section. Can be over-ridden on a per-section basis.

renderSectionFooter?: ?(info: {section: SectionT}) => ?React.Element<any> #

Rendered at the bottom of each section.

renderSectionHeader?: ?(info: {section: SectionT}) => ?React.Element<any> #

Rendered at the top of each section. These stick to the top of the ScrollView by default on +iOS. See stickySectionHeadersEnabled.

sections: $ReadOnlyArray<SectionT> #

The actual data to render, akin to the data prop in <FlatList>.

General shape:

sections: $ReadOnlyArray<{ + data: $ReadOnlyArray<SectionItem>, + renderItem?: ({item: SectionItem, ...}) => ?React.Element<*>, + ItemSeparatorComponent?: ?ReactClass<{highlighted: boolean, ...}>, +}>

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.

Methods #

scrollToLocation(params: object) #

Scrolls to the item at the specified sectionIndex and itemIndex (within the section) +positioned in the viewable area such that viewPosition 0 places it at the top (and may be +covered by a sticky header), 1 at the bottom, and 0.5 centered in the middle. viewOffset is a +fixed number of pixels to offset the final target position, e.g. to compensate for sticky +headers.

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

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.

flashScrollIndicators() #

Displays the scroll indicators momentarily.

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

\ No newline at end of file diff --git a/releases/0.47/docs/segmentedcontrolios.html b/releases/0.47/docs/segmentedcontrolios.html new file mode 100644 index 00000000000..e815553b6ab --- /dev/null +++ b/releases/0.47/docs/segmentedcontrolios.html @@ -0,0 +1,32 @@ +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 + values={['One', 'Two']} + selectedIndex={this.state.selectedIndex} + onChange={(event) => { + this.setState({selectedIndex: event.nativeEvent.selectedSegmentIndex}); + }} +/>

Props #

enabled?: PropTypes.bool #

If false the user won't be able to interact with the control. +Default value is true.

momentary?: PropTypes.bool #

If true, then selecting a segment won't persist visually. +The onValueChange callback will still work as expected.

onChange?: PropTypes.func #

Callback that is called when the user taps a segment; +passes the event as an argument

onValueChange?: PropTypes.func #

Callback that is called when the user taps a segment; +passes the segment's value as an argument

selectedIndex?: PropTypes.number #

The index in props.values of the segment to be (pre)selected.

tintColor?: PropTypes.string #

Accent color of the control.

values?: PropTypes.arrayOf(PropTypes.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!

\ No newline at end of file diff --git a/releases/0.47/docs/settings.html b/releases/0.47/docs/settings.html new file mode 100644 index 00000000000..f278fccede1 --- /dev/null +++ b/releases/0.47/docs/settings.html @@ -0,0 +1,19 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/shadow-props.html b/releases/0.47/docs/shadow-props.html new file mode 100644 index 00000000000..a6a5220d7cc --- /dev/null +++ b/releases/0.47/docs/shadow-props.html @@ -0,0 +1,22 @@ +Shadow Props

Shadow Props #

Props #

iosshadowColor?: color #

Sets the drop shadow color

iosshadowOffset?: ReactPropTypes.shape({ + width: ReactPropTypes.number, + height: ReactPropTypes.number, +}) #

Sets the drop shadow offset

iosshadowOpacity?: ReactPropTypes.number #

Sets the drop shadow opacity (multiplied by the color's alpha component)

iosshadowRadius?: ReactPropTypes.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 diff --git a/releases/0.47/docs/share.html b/releases/0.47/docs/share.html new file mode 100644 index 00000000000..7e1abd875ae --- /dev/null +++ b/releases/0.47/docs/share.html @@ -0,0 +1,22 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/signed-apk-android.html b/releases/0.47/docs/signed-apk-android.html new file mode 100644 index 00000000000..6fbdce7b522 --- /dev/null +++ b/releases/0.47/docs/signed-apk-android.html @@ -0,0 +1,46 @@ +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,

... +android { + ... + defaultConfig { ... } + signingConfigs { + release { + if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) { + storeFile file(MYAPP_RELEASE_STORE_FILE) + storePassword MYAPP_RELEASE_STORE_PASSWORD + keyAlias MYAPP_RELEASE_KEY_ALIAS + keyPassword MYAPP_RELEASE_KEY_PASSWORD + } + } + } + buildTypes { + release { + ... + signingConfig signingConfigs.release + } + } +} +...

Generating the release APK #

Simply run the following in a terminal:

$ cd android && ./gradlew assembleRelease

Gradle's assembleRelease will bundle all the JavaScript needed to run your app into the APK. If you need to change the way the JavaScript bundle and/or drawable resources are bundled (e.g. if you changed the default file/folder names or the general structure of the project), have a look at android/app/build.gradle to see how you can update it to reflect these changes.

The generated APK can be found under android/app/build/outputs/apk/app-release.apk, and is ready to be distributed.

Testing the release build of your app #

Before uploading the release build to the Play Store, make sure you test it thoroughly. First uninstall any previous version of the app you already have installed. Install it on the device using:

$ react-native run-android --variant=release

Note that --variant=release is only available if you've set up signing as described above.

You can kill any running packager instances, all your framework and JavaScript code is bundled in the APK's assets.

Enabling Proguard to reduce the size of the APK (optional) #

Proguard is a tool that can slightly reduce the size of the APK. It does this by stripping parts of the React Native Java bytecode (and its dependencies) that your app is not using.

IMPORTANT: Make sure to thoroughly test your app if you've enabled Proguard. Proguard often requires configuration specific to each native library you're using. See app/proguard-rules.pro.

To enable Proguard, edit android/app/build.gradle:

/** + * Run Proguard to shrink the Java bytecode in release builds. + */ +def enableProguardInReleaseBuilds = true

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

\ No newline at end of file diff --git a/releases/0.47/docs/slider.html b/releases/0.47/docs/slider.html new file mode 100644 index 00000000000..429038995ed --- /dev/null +++ b/releases/0.47/docs/slider.html @@ -0,0 +1,33 @@ +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?: 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?: 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!

\ No newline at end of file diff --git a/releases/0.47/docs/snapshotviewios.html b/releases/0.47/docs/snapshotviewios.html new file mode 100644 index 00000000000..6c1f20f0b39 --- /dev/null +++ b/releases/0.47/docs/snapshotviewios.html @@ -0,0 +1,19 @@ +SnapshotViewIOS

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 diff --git a/releases/0.47/docs/state.html b/releases/0.47/docs/state.html new file mode 100644 index 00000000000..340b4b362a7 --- /dev/null +++ b/releases/0.47/docs/state.html @@ -0,0 +1,58 @@ +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 { + constructor(props) { + super(props); + this.state = {showText: true}; + + // Toggle the state every second + setInterval(() => { + this.setState(previousState => { + return { showText: !previousState.showText }; + }); + }, 1000); + } + + render() { + let display = this.state.showText ? this.props.text : ' '; + return ( + <Text>{display}</Text> + ); + } +} + +export default class BlinkApp extends Component { + render() { + return ( + <View> + <Blink text='I love to blink' /> + <Blink text='Yes blinking is so great' /> + <Blink text='Why did they ever take this out of HTML' /> + <Blink text='Look at me look at me look at me' /> + </View> + ); + } +} + +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => 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 diff --git a/releases/0.47/docs/statusbar.html b/releases/0.47/docs/statusbar.html new file mode 100644 index 00000000000..b60efc538df --- /dev/null +++ b/releases/0.47/docs/statusbar.html @@ -0,0 +1,44 @@ +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 + backgroundColor="blue" + barStyle="light-content" + /> + <Navigator + initialRoute={{statusBarHidden: true}} + renderScene={(route, navigator) => + <View> + <StatusBar hidden={route.statusBarHidden} /> + ... + </View> + } + /> + </View>

Imperative API #

For cases where using a component is not ideal, there is also an imperative +API exposed as static functions on the component. It is however not recommended +to use the static API and the component for the same prop because any value +set by the static API will get overriden by the one set by the component in +the next render.

Constants #

currentHeight (Android only) The height of the status bar.

Props #

animated?: boolean #

If the transition between status bar property changes should be animated. +Supported for backgroundColor, barStyle and hidden.

barStyle?: literal | literal | literal #

Sets the color of the status bar text.

hidden?: boolean #

If the status bar is hidden.

androidbackgroundColor?: $FlowFixMe #

The background color of the status bar.

androidtranslucent?: boolean #

If the status bar is translucent. +When translucent is set to true, the app will draw under the status bar. +This is useful when using a semi transparent status bar color.

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!

\ No newline at end of file diff --git a/releases/0.47/docs/statusbarios.html b/releases/0.47/docs/statusbarios.html new file mode 100644 index 00000000000..0b66bb0d188 --- /dev/null +++ b/releases/0.47/docs/statusbarios.html @@ -0,0 +1,19 @@ +StatusBarIOS

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 diff --git a/releases/0.47/docs/style.html b/releases/0.47/docs/style.html new file mode 100644 index 00000000000..32ac15a33db --- /dev/null +++ b/releases/0.47/docs/style.html @@ -0,0 +1,48 @@ +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'; + +export default class LotsOfStyles extends Component { + render() { + return ( + <View> + <Text style={styles.red}>just red</Text> + <Text style={styles.bigblue}>just bigblue</Text> + <Text style={[styles.bigblue, styles.red]}>bigblue, then red</Text> + <Text style={[styles.red, styles.bigblue]}>red, then bigblue</Text> + </View> + ); + } +} + +const styles = StyleSheet.create({ + bigblue: { + color: 'blue', + fontWeight: 'bold', + fontSize: 30, + }, + red: { + color: 'red', + }, +}); + +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => 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 diff --git a/releases/0.47/docs/stylesheet.html b/releases/0.47/docs/stylesheet.html new file mode 100644 index 00000000000..551fcda750a --- /dev/null +++ b/releases/0.47/docs/stylesheet.html @@ -0,0 +1,82 @@ +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, + borderColor: '#d6d7da', + }, + title: { + fontSize: 19, + fontWeight: 'bold', + }, + activeTitle: { + color: 'red', + }, +});

Use a StyleSheet:

<View style={styles.container}> + <Text style={[styles.title, this.props.isActive && styles.activeTitle]} /> +</View>

Code quality:

  • By moving styles away from the render function, you're making the code +easier to understand.
  • Naming the styles is a good way to add meaning to the low level components +in the render function.

Performance:

  • Making a stylesheet from a style object makes it possible to refer to it +by ID instead of creating a new style object every time.
  • It also allows to send the style only once through the bridge. All +subsequent uses are going to refer an id (not implemented yet).

Methods #

static setStyleAttributePreprocessor(property, process) #

WARNING: EXPERIMENTAL. Breaking changes will probably happen a lot and will +not be reliably announced. The whole thing might be deleted, who knows? Use +at your own risk.

Sets a function to use to pre-process a style property value. This is used +internally to process color and transform values. You should not use this +unless you really know what you are doing and have exhausted other options.

static create(obj) #

Creates a StyleSheet style reference from the given object.

Properties #

hairlineWidth: CallExpression #

This is defined as the width of a thin line on the platform. It can be +used as the thickness of a border or division between two elements. +Example:

{ + borderBottomColor: '#bbb', + borderBottomWidth: StyleSheet.hairlineWidth + }

This constant will always be a round number of pixels (so a line defined +by it look crisp) and will try to match the standard width of a thin line +on the underlying platform. However, you should not rely on it being a +constant size, because on different platforms and screen densities its +value may be calculated differently.

A line with hairline width may not be visible if your simulator is downscaled.

absoluteFill: CallExpression #

A very common pattern is to create overlays with position absolute and zero positioning, +so absoluteFill can be used for convenience and to reduce duplication of these repeated +styles.

absoluteFillObject: ObjectExpression #

Sometimes you may want absoluteFill but with a couple tweaks - absoluteFillObject can be +used to create a customized entry in a StyleSheet, e.g.:

const styles = StyleSheet.create({ + wrapper: { + ...StyleSheet.absoluteFillObject, + top: 10, + backgroundColor: 'transparent', + }, + });

flatten: CallExpression #

Flattens an array of style objects, into one aggregated style object. +Alternatively, this method can be used to lookup IDs, returned by +StyleSheet.register.

NOTE: Exercise caution as abusing this can tax you in terms of +optimizations.

IDs enable optimizations through the bridge and memory in general. Refering +to style objects directly will deprive you of these optimizations.

Example:

var styles = StyleSheet.create({ + listItem: { + flex: 1, + fontSize: 16, + color: 'white' + }, + selectedListItem: { + color: 'green' + } +}); + +StyleSheet.flatten([styles.listItem, styles.selectedListItem]) +// returns { flex: 1, fontSize: 16, color: 'green' }

Alternative use:

StyleSheet.flatten(styles.listItem); +// return { flex: 1, fontSize: 16, color: 'white' } +// Simply styles.listItem would return its ID (number)

This method internally uses StyleSheetRegistry.getStyleByID(style) +to resolve style objects represented by IDs. Thus, an array of style +objects (instances of StyleSheet.create), are individually resolved to, +their respective objects, merged as one and then returned. This also explains +the alternative use.

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

\ No newline at end of file diff --git a/releases/0.47/docs/switch.html b/releases/0.47/docs/switch.html new file mode 100644 index 00000000000..7d70594862a --- /dev/null +++ b/releases/0.47/docs/switch.html @@ -0,0 +1,25 @@ +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?: PropTypes.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?: PropTypes.func #

Invoked with the new value when the value changes.

testID?: PropTypes.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?: PropTypes.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!

\ No newline at end of file diff --git a/releases/0.47/docs/systrace.html b/releases/0.47/docs/systrace.html new file mode 100644 index 00000000000..c9d8a9307d9 --- /dev/null +++ b/releases/0.47/docs/systrace.html @@ -0,0 +1,30 @@ +Systrace

Systrace #

Methods #

static getUserTimingPolyfill() #

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 +if you want to find traces which spend too much time in JSON.

static measureMethods(object, objectName, methodNames) #

Measures multiple methods of a class. For example, you can do: +Systrace.measureMethods(JSON, 'JSON', ['parse', 'stringify']);

@param object +@param objectName +@param methodNames Map from method names to method display names.

static measure(objName, fnName, func) #

Returns an profiled version of the input function. For example, you can: +JSON.parse = Systrace.measure('JSON', 'parse', JSON.parse);

@param objName +@param fnName +@param {function} func +@return {function} replacement function

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

\ No newline at end of file diff --git a/releases/0.47/docs/tabbarios-item.html b/releases/0.47/docs/tabbarios-item.html new file mode 100644 index 00000000000..4b90459aa66 --- /dev/null +++ b/releases/0.47/docs/tabbarios-item.html @@ -0,0 +1,43 @@ +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?: 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?: 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 diff --git a/releases/0.47/docs/tabbarios.html b/releases/0.47/docs/tabbarios.html new file mode 100644 index 00000000000..f21368350e0 --- /dev/null +++ b/releases/0.47/docs/tabbarios.html @@ -0,0 +1,25 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/testing.html b/releases/0.47/docs/testing.html new file mode 100644 index 00000000000..83b18bc4220 --- /dev/null +++ b/releases/0.47/docs/testing.html @@ -0,0 +1,30 @@ +Running Tests and Contributing

Running Tests and Contributing #

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.

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 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 diff --git a/releases/0.47/docs/text.html b/releases/0.47/docs/text.html new file mode 100644 index 00000000000..b0244bc3645 --- /dev/null +++ b/releases/0.47/docs/text.html @@ -0,0 +1,184 @@ +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'; + +export default class TextInANest extends Component { + constructor(props) { + super(props); + this.state = { + titleText: "Bird's Nest", + bodyText: 'This is not really a bird nest.' + }; + } + + render() { + return ( + <Text style={styles.baseText}> + <Text style={styles.titleText} onPress={this.onPressTitle}> + {this.state.titleText}{'\n'}{'\n'} + </Text> + <Text numberOfLines={5}> + {this.state.bodyText} + </Text> + </Text> + ); + } +} + +const styles = StyleSheet.create({ + baseText: { + fontFamily: 'Cochin', + }, + titleText: { + fontSize: 20, + fontWeight: 'bold', + }, +}); + +// 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?: 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

nativeID?: PropTypes.string #

Used to locate this view from native code.

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?: 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?: PropTypes.bool #

Lets the user select text, to use the native copy and paste functionality.

style?: style #

color color
fontFamily ReactPropTypes.string
fontSize ReactPropTypes.number
fontStyle ReactPropTypes.oneOf(['normal', 'italic'])
fontWeight ReactPropTypes.oneOf( + ['normal' /*default*/, '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 ReactPropTypes.number
textAlign ReactPropTypes.oneOf( + ['auto' /*default*/, 'left', 'right', 'center', 'justify'] +)

Specifies text alignment. The value 'justify' is only supported on iOS and +fallbacks to left on Android.

textDecorationLine ReactPropTypes.oneOf( + ['none' /*default*/, 'underline', 'line-through', 'underline line-through'] +)
textShadowColor color
textShadowOffset ReactPropTypes.shape( + {width: ReactPropTypes.number, height: ReactPropTypes.number} +)
textShadowRadius ReactPropTypes.number
androidincludeFontPadding ReactPropTypes.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 ReactPropTypes.oneOf( + ['auto' /*default*/, 'top', 'bottom', 'center'] +)
iosfontVariant ReactPropTypes.arrayOf( + ReactPropTypes.oneOf([ + 'small-caps', + 'oldstyle-nums', + 'lining-nums', + 'tabular-nums', + 'proportional-nums', + ]) +)
iosletterSpacing ReactPropTypes.number
iostextDecorationColor color
iostextDecorationStyle ReactPropTypes.oneOf( + ['solid' /*default*/, 'double', 'dotted','dashed'] +)
ioswritingDirection ReactPropTypes.oneOf( + ['auto' /*default*/, '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

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'; + +export default class BoldAndBeautiful extends Component { + render() { + return ( + <Text style={{fontWeight: 'bold'}}> + I am bold + <Text style={{color: 'red'}}> + and red + </Text> + </Text> + ); + } +} + +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => 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'; + +export default class BlueIsCool extends Component { + render() { + return ( + <Text> + There is a blue square + <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> + in between my text. + </Text> + ); + } +} + +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => 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> +// Text container: all the text flows as if it was one +// |First part | +// |and second | +// |part | + +<View> + <Text>First part and </Text> + <Text>second part</Text> +</View> +// View container: each text is its own block +// |First part | +// |and | +// |second part|

Limited Style Inheritance #

On the web, the usual way to set a font family and size for the entire document is to take advantage of inherited CSS properties like so:

/* CSS, *not* React Native */ +html { + font-family: 'lucida grande', tahoma, verdana, arial, sans-serif; + font-size: 11px; + color: #141823; +}

All elements in the document will inherit this font unless they or one of their parents specifies a new rule.

In React Native, we are more strict about it: you must wrap all the text nodes inside of a <Text> component; you cannot have a text node directly under a <View>.

// BAD: will raise exception, can't have a text node as child of a <View> +<View> + Some text +</View> + +// GOOD +<View> + <Text> + Some text + </Text> +</View>

You also lose the ability to set up a default font for an entire subtree. The recommended way to use consistent fonts and sizes across your application is to create a component MyAppText that includes them and use this component across your app. You can also use this component to make more specific components like MyAppHeaderText for other kinds of text.

<View> + <MyAppText>Text styled with the default font for the entire application</MyAppText> + <MyAppHeaderText>Text styled as a header</MyAppHeaderText> +</View>

Assuming that MyAppText is a component that simply renders out its children into a Text component with styling, then MyAppHeaderText can be defined as follows:

class MyAppHeaderText extends Component { + render() { + <MyAppText> + <Text style={{fontSize: 20}}> + {this.props.children} + </Text> + </MyAppText> + } +}

Composing MyAppText in this way ensures that we get the styles from a top-level component, but leaves us the ability to add / override them in specific use cases.

React Native still has the concept of style inheritance, but limited to text subtrees. In this case, the second part will be both bold and red.

<Text style={{fontWeight: 'bold'}}> + I am bold + <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!

\ No newline at end of file diff --git a/releases/0.47/docs/textinput.html b/releases/0.47/docs/textinput.html new file mode 100644 index 00000000000..3ea8ae08fe7 --- /dev/null +++ b/releases/0.47/docs/textinput.html @@ -0,0 +1,203 @@ +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 +onChangeText events to read the user input. There are also other events, +such as onSubmitEditing and onFocus that can be subscribed to. A simple +example:

import React, { Component } from 'react'; +import { AppRegistry, TextInput } from 'react-native'; + +export default class UselessTextInput extends Component { + constructor(props) { + super(props); + this.state = { text: 'Useless Placeholder' }; + } + + render() { + return ( + <TextInput + style={{height: 40, borderColor: 'gray', borderWidth: 1}} + onChangeText={(text) => this.setState({text})} + value={this.state.text} + /> + ); + } +} + +// 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 +in a View:

import React, { Component } from 'react'; +import { AppRegistry, View, TextInput } from 'react-native'; + +class UselessTextInput extends Component { + render() { + return ( + <TextInput + {...this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below + editable = {true} + maxLength = {40} + /> + ); + } +} + +export default class UselessTextInputMultiline extends Component { + constructor(props) { + super(props); + this.state = { + text: 'Useless Multiline Placeholder', + }; + } + + // If you type something in the text box that is a color, the background will change to that + // color. + render() { + return ( + <View style={{ + backgroundColor: this.state.text, + borderBottomColor: '#000000', + borderBottomWidth: 1 }} + > + <UselessTextInput + multiline = {true} + numberOfLines = {4} + onChangeText={(text) => this.setState({text})} + value={this.state.text} + /> + </View> + ); + } +} + +// 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 +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 +in the correct position, or to not display the border by setting +underlineColorAndroid to transparent.

Note that on Android performing text selection in input can change +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?: 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?: 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?: 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?: 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?: PropTypes.func #

Callback that is called when the text input selection is changed. +This will be called with +{ 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?: 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?: 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?: 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?: 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?: 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?: PropTypes.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!

\ No newline at end of file diff --git a/releases/0.47/docs/textstyleproptypes.html b/releases/0.47/docs/textstyleproptypes.html new file mode 100644 index 00000000000..2faabc7606f --- /dev/null +++ b/releases/0.47/docs/textstyleproptypes.html @@ -0,0 +1,47 @@ +TextStylePropTypes

TextStylePropTypes #

Props #

color?: color #

fontFamily?: ReactPropTypes.string #

fontSize?: ReactPropTypes.number #

fontStyle?: ReactPropTypes.oneOf(['normal', 'italic']) #

fontWeight?: ReactPropTypes.oneOf( + ['normal' /*default*/, '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?: ReactPropTypes.number #

textAlign?: ReactPropTypes.oneOf( + ['auto' /*default*/, 'left', 'right', 'center', 'justify'] +) #

Specifies text alignment. The value 'justify' is only supported on iOS and +fallbacks to left on Android.

textDecorationLine?: ReactPropTypes.oneOf( + ['none' /*default*/, 'underline', 'line-through', 'underline line-through'] +) #

textShadowColor?: color #

textShadowOffset?: ReactPropTypes.shape( + {width: ReactPropTypes.number, height: ReactPropTypes.number} +) #

textShadowRadius?: ReactPropTypes.number #

androidincludeFontPadding?: ReactPropTypes.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?: ReactPropTypes.oneOf( + ['auto' /*default*/, 'top', 'bottom', 'center'] +) #

iosfontVariant?: ReactPropTypes.arrayOf( + ReactPropTypes.oneOf([ + 'small-caps', + 'oldstyle-nums', + 'lining-nums', + 'tabular-nums', + 'proportional-nums', + ]) +) #

iosletterSpacing?: ReactPropTypes.number #

iostextDecorationColor?: color #

iostextDecorationStyle?: ReactPropTypes.oneOf( + ['solid' /*default*/, 'double', 'dotted','dashed'] +) #

ioswritingDirection?: ReactPropTypes.oneOf( + ['auto' /*default*/, 'ltr', 'rtl'] +) #

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

\ No newline at end of file diff --git a/releases/0.47/docs/timepickerandroid.html b/releases/0.47/docs/timepickerandroid.html new file mode 100644 index 00000000000..7a58606085d --- /dev/null +++ b/releases/0.47/docs/timepickerandroid.html @@ -0,0 +1,38 @@ +TimePickerAndroid

TimePickerAndroid #

Opens the standard Android time picker dialog.

Example #

try { + const {action, hour, minute} = await TimePickerAndroid.open({ + hour: 14, + minute: 0, + is24Hour: false, // Will display '2 PM' + }); + if (action !== TimePickerAndroid.dismissedAction) { + // Selected hour (0-23), minute (0-59) + } +} catch ({code, message}) { + console.warn('Cannot open time picker', message); +}

Methods #

static open(options) #

Opens the standard Android time picker dialog.

The available keys for the options object are: + hour (0-23) - the hour to show, defaults to the current time + minute (0-59) - the minute to show, defaults to the current time + * is24Hour (boolean) - If true, the picker uses the 24-hour format. If false, + the picker shows an AM/PM chooser. If undefined, the default for the current locale + 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!

\ No newline at end of file diff --git a/releases/0.47/docs/timers.html b/releases/0.47/docs/timers.html new file mode 100644 index 00000000000..74b7ba927de --- /dev/null +++ b/releases/0.47/docs/timers.html @@ -0,0 +1,35 @@ +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) +// later, on animation completion: +InteractionManager.clearInteractionHandle(handle); +// queued tasks run if all handles were cleared

TimerMixin #

We found out that the primary cause of fatals in apps created with React Native was due to timers firing after a component was unmounted. To solve this recurring issue, we introduced TimerMixin. If you include TimerMixin, then you can replace your calls to setTimeout(fn, 500) with this.setTimeout(fn, 500) (just prepend this.) and everything will be properly cleaned up for you when the component unmounts.

This library does not ship with React Native - in order to use it on your project, you will need to install it with npm i react-timer-mixin --save from your project directory.

import TimerMixin from 'react-timer-mixin'; + +var Component = React.createClass({ + mixins: [TimerMixin], + componentDidMount: function() { + this.setTimeout( + () => { console.log('I do not leak!'); }, + 500 + ); + } +});

This will eliminate a lot of hard work tracking down bugs, such as crashes caused by timeouts firing after a component has been unmounted.

Keep in mind that if you use ES6 classes for your React components there is no built-in API for mixins. To use TimerMixin with ES6 classes, we recommend react-mixin.

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

\ No newline at end of file diff --git a/releases/0.47/docs/toastandroid.html b/releases/0.47/docs/toastandroid.html new file mode 100644 index 00000000000..afd401bf232 --- /dev/null +++ b/releases/0.47/docs/toastandroid.html @@ -0,0 +1,22 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/toolbarandroid.html b/releases/0.47/docs/toolbarandroid.html new file mode 100644 index 00000000000..01a945e6396 --- /dev/null +++ b/releases/0.47/docs/toolbarandroid.html @@ -0,0 +1,57 @@ +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 +should only be used in DEV mode where require('./some_icon.png') translates into a packager +URL. In release mode you should always use a drawable resource for these icons. Using +require('./some_icon.png') will do this automatically for you, so as long as you don't +explicitly use e.g. {uri: 'http://...'}, you will be good.

Example:

render: function() { + return ( + <ToolbarAndroid + logo={require('./app_logo.png')} + title="AwesomeApp" + actions={[{title: 'Settings', icon: require('./icon_settings.png'), show: 'always'}]} + onActionSelected={this.onActionSelected} /> + ) +}, +onActionSelected: function(position) { + if (position === 0) { // index of 'Settings' + showSettings(); + } +}

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?: 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?: 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?: 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?: PropTypes.string #

Sets the toolbar subtitle.

subtitleColor?: color #

Sets the toolbar subtitle color.

testID?: PropTypes.string #

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

title?: PropTypes.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!

\ No newline at end of file diff --git a/releases/0.47/docs/touchablehighlight.html b/releases/0.47/docs/touchablehighlight.html new file mode 100644 index 00000000000..640b45d4088 --- /dev/null +++ b/releases/0.47/docs/touchablehighlight.html @@ -0,0 +1,40 @@ +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, +for example if the backgroundColor of the wrapped view isn't explicitly set +to an opaque color.

TouchableHighlight must have one child (not zero or more than one). +If you wish to have several child components, wrap them in a View.

Example:

renderButton: function() { + return ( + <TouchableHighlight onPress={this._onPressButton}> + <Image + style={styles.button} + source={require('./myButton.png')} + /> + </TouchableHighlight> + ); +},

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. +magnification: Defaults to 1.0.

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

\ No newline at end of file diff --git a/releases/0.47/docs/touchablenativefeedback.html b/releases/0.47/docs/touchablenativefeedback.html new file mode 100644 index 00000000000..35699d6cc43 --- /dev/null +++ b/releases/0.47/docs/touchablenativefeedback.html @@ -0,0 +1,48 @@ +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 +RCTView node with some additional properties set.

Background drawable of native feedback touchable can be customized with +background property.

Example:

renderButton: function() { + return ( + <TouchableNativeFeedback + onPress={this._onPressButton} + background={TouchableNativeFeedback.SelectableBackground()}> + <View style={{width: 150, height: 100, backgroundColor: 'red'}}> + <Text style={{margin: 30}}>Button</Text> + </View> + </TouchableNativeFeedback> + ); +},

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?: 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 +fallback to background.

Methods #

static SelectableBackground() #

Creates an object that represents android theme's default background for +selectable elements (?android:attr/selectableItemBackground).

static SelectableBackgroundBorderless() #

Creates an object that represent android theme's default background for borderless +selectable elements (?android:attr/selectableItemBackgroundBorderless). +Available on android API level 21+.

static Ripple(color: string, borderless: boolean) #

Creates an object that represents ripple drawable with specified color (as a +string). If property borderless evaluates to true the ripple will +render outside of the view bounds (see native actionbar buttons as an +example of that behavior). This background type is available on Android +API level 21+.

Parameters:
Name and TypeDescription
color

string

The ripple color

borderless

boolean

If the ripple can render outside it's bounds

static canUseNativeForeground() #

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

\ No newline at end of file diff --git a/releases/0.47/docs/touchableopacity.html b/releases/0.47/docs/touchableopacity.html new file mode 100644 index 00000000000..c454d7af9f8 --- /dev/null +++ b/releases/0.47/docs/touchableopacity.html @@ -0,0 +1,31 @@ +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 ( + <TouchableOpacity onPress={this._onPressButton}> + <Image + style={styles.button} + source={require('./myButton.png')} + /> + </TouchableOpacity> + ); +},

Props #

activeOpacity?: PropTypes.number #

Determines what the opacity of the wrapped view should be when touch is +active. Defaults to 0.2.

focusedOpacity?: PropTypes.number #

tvParallaxProperties?: PropTypes.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 diff --git a/releases/0.47/docs/touchablewithoutfeedback.html b/releases/0.47/docs/touchablewithoutfeedback.html new file mode 100644 index 00000000000..7b1f0345d23 --- /dev/null +++ b/releases/0.47/docs/touchablewithoutfeedback.html @@ -0,0 +1,36 @@ +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?: 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?: 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 +is disabled. Ensure you pass in a constant to reduce memory allocations.

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

\ No newline at end of file diff --git a/releases/0.47/docs/transforms.html b/releases/0.47/docs/transforms.html new file mode 100644 index 00000000000..cae754a0f86 --- /dev/null +++ b/releases/0.47/docs/transforms.html @@ -0,0 +1,34 @@ +Transforms

Transforms #

Props #

decomposedMatrix?: DecomposedMatrixPropType #

transform?: ReactPropTypes.arrayOf( + ReactPropTypes.oneOfType([ + ReactPropTypes.shape({perspective: ReactPropTypes.number}), + ReactPropTypes.shape({rotate: ReactPropTypes.string}), + ReactPropTypes.shape({rotateX: ReactPropTypes.string}), + ReactPropTypes.shape({rotateY: ReactPropTypes.string}), + ReactPropTypes.shape({rotateZ: ReactPropTypes.string}), + ReactPropTypes.shape({scale: ReactPropTypes.number}), + ReactPropTypes.shape({scaleX: ReactPropTypes.number}), + ReactPropTypes.shape({scaleY: ReactPropTypes.number}), + ReactPropTypes.shape({translateX: ReactPropTypes.number}), + ReactPropTypes.shape({translateY: ReactPropTypes.number}), + ReactPropTypes.shape({skewX: ReactPropTypes.string}), + ReactPropTypes.shape({skewY: ReactPropTypes.string}) + ]) +) #

transformMatrix?: TransformMatrixPropType #

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

\ No newline at end of file diff --git a/releases/0.47/docs/troubleshooting.html b/releases/0.47/docs/troubleshooting.html new file mode 100644 index 00000000000..6cb251b8b20 --- /dev/null +++ b/releases/0.47/docs/troubleshooting.html @@ -0,0 +1,27 @@ +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', + 'RCTNetwork', + 'RCTWebSocket', +]

Next, make sure you have run pod install and that a Pods/ directory has been created in your project with React installed. CocoaPods will instruct you to use the generated .xcworkspace file henceforth to be able to use these installed dependencies.

Argument list too long: recursive header expansion failed #

In the project's build settings, User Search Header Paths and Header Search Paths are two configs that specify where Xcode should look for #import header files specified in the code. For Pods, CocoaPods uses a default array of specific folders to look in. Verify that this particular config is not overwritten, and that none of the folders configured are too large. If one of the folders is a large folder, Xcode will attempt to recursively search the entire directory and throw above error at some point.

To revert the User Search Header Paths and Header Search Paths build settings to their defaults set by CocoaPods - select the entry in the Build Settings panel, and hit delete. It will remove the custom override and return to the CocoaPod defaults.

No transports available #

React Native implements a polyfill for WebSockets. These polyfills are initialized as part of the react-native module that you include in your application through import React from 'react'. If you load another module that requires WebSockets, such as Firebase, be sure to load/require it after react-native:

import React from 'react'; +import Firebase from 'firebase';

Shell Command Unresponsive Exception #

If you encounter a ShellCommandUnresponsiveException exception such as:

Execution failed for task ':app:installDebug'. + com.android.builder.testing.api.DeviceException: com.android.ddmlib.ShellCommandUnresponsiveException

Try downgrading your Gradle version to 1.2.3 in android/build.gradle.

react-native init hangs #

If you run into issues where running react-native init hangs in your system, try running it again in verbose mode and refering to #2797 for common causes:

react-native init --verbose

Unable to start react-native package manager (on Linux) #

Case 1: Error "code":"ENOSPC","errno":"ENOSPC" #

Issue caused by the number of directories inotify (used by watchman on Linux) can monitor. To solve it, just run this command in your terminal window

echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

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

\ No newline at end of file diff --git a/releases/0.47/docs/tutorial.html b/releases/0.47/docs/tutorial.html new file mode 100644 index 00000000000..f342209ad70 --- /dev/null +++ b/releases/0.47/docs/tutorial.html @@ -0,0 +1,41 @@ +Learn the Basics

Learn the Basics #

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'; + +export default class HelloWorldApp extends Component { + render() { + return ( + <Text>Hello world!</Text> + ); + } +} + +// skip this line if using Create React Native App +AppRegistry.registerComponent('AwesomeProject', () => 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 App.js, 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.

Components #

So this code is defining HelloWorldApp, a new Component. 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.

+ + +

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 diff --git a/releases/0.47/docs/understanding-cli.html b/releases/0.47/docs/understanding-cli.html new file mode 100644 index 00000000000..5c7e5d91293 --- /dev/null +++ b/releases/0.47/docs/understanding-cli.html @@ -0,0 +1,29 @@ +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 +from commands.js and added as possible CLI commands. E.G. the react-native link command, exists in the +react-native/local-cli/link folder, and is +required in commands.js, which will register it as a documented command to be exposed to the CLI.

Command definitions #

At the end of each command entry is an export. The export is an object with a function to perform, description of the command, and the command name. The object structure for the link command looks like so:

module.exports = { + func: link, + description: 'links all native dependencies', + name: 'link [packageName]', +};

Parameters #

The command name identifies the parameters that a command would expect. When the command parameter is surrounded by greater-than, less-than symbols < >, this indicates that the parameter is expected. When a parameter is surrounded by brackets [ ], this indicates that the parameter is optional.

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

\ No newline at end of file diff --git a/releases/0.47/docs/upgrading.html b/releases/0.47/docs/upgrading.html new file mode 100644 index 00000000000..80d9d52bed3 --- /dev/null +++ b/releases/0.47/docs/upgrading.html @@ -0,0 +1,50 @@ +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 #

+ +

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; +<<<<<<< ours + CODE_SIGN_IDENTITY = "iPhone Developer"; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/HockeySDK.embeddedframework", + "$(PROJECT_DIR)/HockeySDK-iOS/HockeySDK.embeddedframework", + ); +======= + CURRENT_PROJECT_VERSION = 1; +>>>>>>> theirs + HEADER_SEARCH_PATHS = ( + "$(inherited)", + /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 +# 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 +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 diff --git a/releases/0.47/docs/using-a-listview.html b/releases/0.47/docs/using-a-listview.html new file mode 100644 index 00000000000..b22e4ef0fa9 --- /dev/null +++ b/releases/0.47/docs/using-a-listview.html @@ -0,0 +1,99 @@ +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.

If you want to render a set of data broken into logical sections, maybe with section headers, similar to UITableViews on iOS, then a SectionList is the way to go.

One of the most common uses for a list view 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 diff --git a/releases/0.47/docs/using-a-scrollview.html b/releases/0.47/docs/using-a-scrollview.html new file mode 100644 index 00000000000..5556ba34d57 --- /dev/null +++ b/releases/0.47/docs/using-a-scrollview.html @@ -0,0 +1,65 @@ +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'; + +export default class IScrolledDownAndWhatHappenedNextShockedMe extends Component { + render() { + return ( + <ScrollView> + <Text style={{fontSize:96}}>Scroll me plz</Text> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Text style={{fontSize:96}}>If you like</Text> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Text style={{fontSize:96}}>Scrolling down</Text> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Text style={{fontSize:96}}>What's the best</Text> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Text style={{fontSize:96}}>Framework around?</Text> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Image source={require('./img/favicon.png')} /> + <Text style={{fontSize:80}}>React Native</Text> + </ScrollView> + ); + } +} + +// skip these lines if using Create React Native App +AppRegistry.registerComponent( + 'AwesomeProject', + () => IScrolledDownAndWhatHappenedNextShockedMe);

ScrollViews 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 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.

The 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 FlatList instead. So let's learn about list views next.

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

\ No newline at end of file diff --git a/releases/0.47/docs/vibration.html b/releases/0.47/docs/vibration.html new file mode 100644 index 00000000000..c245f325d40 --- /dev/null +++ b/releases/0.47/docs/vibration.html @@ -0,0 +1,19 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/vibrationios.html b/releases/0.47/docs/vibrationios.html new file mode 100644 index 00000000000..68d62333394 --- /dev/null +++ b/releases/0.47/docs/vibrationios.html @@ -0,0 +1,22 @@ +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!

\ No newline at end of file diff --git a/releases/0.47/docs/view.html b/releases/0.47/docs/view.html new file mode 100644 index 00000000000..8c129dd1872 --- /dev/null +++ b/releases/0.47/docs/view.html @@ -0,0 +1,150 @@ +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 +native view equivalent on whatever platform React Native is running on, whether that is a +UIView, <div>, android.view, etc.

View is designed to be nested inside other views and can have 0 to many children of any type.

This example creates a View that wraps two colored boxes and a text component in a row with +padding.

class ViewColoredBoxesWithText extends Component { + render() { + return ( + <View style={{flexDirection: 'row', height: 100, padding: 20}}> + <View style={{backgroundColor: 'blue', flex: 0.3}} /> + <View style={{backgroundColor: 'red', flex: 0.5}} /> + <Text>Hello World!</Text> + </View> + ); + } +}

Views are designed to be used with StyleSheet for clarity +and performance, although inline styles are also supported.

Synthetic Touch Events #

For View responder props (e.g., onResponderMove), the synthetic touch event passed to them +are of 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.

Props #

accessibilityLabel?: PropTypes.node #

Overrides the text that's read by the screen reader when the user interacts +with the element. By default, the label is constructed by traversing all the +children and accumulating all the Text nodes separated by space.

accessible?: PropTypes.bool #

When true, indicates that the view is an accessibility element. By default, +all the touchable elements are accessible.

hitSlop?: {top: number, left: number, bottom: number, right: number} #

This defines how far a touch event can start away from the view. +Typical interface guidelines recommend touch targets that are at least +30 - 40 points/density-independent pixels.

For example, if a touchable view has a height of 20 the touchable height can be extended to +40 with hitSlop={{top: 10, bottom: 10, left: 0, right: 0}}

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.

nativeID?: PropTypes.string #

Used to locate this view from native classes.

This disables the 'layout-only view removal' optimization for this view!

onAccessibilityTap?: PropTypes.func #

When accessible is true, the system will try to invoke this function +when the user performs accessibility tap gesture.

onLayout?: PropTypes.func #

Invoked on mount and layout changes with:

{nativeEvent: { layout: {x, y, width, height}}}

This event is fired immediately once the layout has been calculated, but +the new layout may not yet be reflected on the screen at the time the +event is received, especially if a layout animation is in progress.

onMagicTap?: PropTypes.func #

When accessible is true, the system will invoke this function when the +user performs the magic tap gesture.

onMoveShouldSetResponder?: PropTypes.func #

Does this view want to "claim" touch responsiveness? This is called for every touch move on +the View when it is not the responder.

View.props.onMoveShouldSetResponder: (event) => [true | false], where event is a +synthetic touch event as described above.

onMoveShouldSetResponderCapture?: PropTypes.func #

If a parent View wants to prevent a child View from becoming responder on a move, +it should have this handler which returns true.

View.props.onMoveShouldSetResponderCapture: (event) => [true | false], where event is a +synthetic touch event as described above.

onResponderGrant?: PropTypes.func #

The View is now responding for touch events. This is the time to highlight and show the user +what is happening.

View.props.onResponderGrant: (event) => {}, where event is a synthetic touch event as +described above.

onResponderMove?: PropTypes.func #

The user is moving their finger.

View.props.onResponderMove: (event) => {}, where event is a synthetic touch event as +described above.

onResponderReject?: PropTypes.func #

Another responder is already active and will not release it to that View asking to be +the responder.

View.props.onResponderReject: (event) => {}, where event is a synthetic touch event as +described above.

onResponderRelease?: PropTypes.func #

Fired at the end of the touch.

View.props.onResponderRelease: (event) => {}, where event is a synthetic touch event as +described above.

onResponderTerminate?: PropTypes.func #

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 (e.g., happens +with control center/ notification center on iOS)

View.props.onResponderTerminate: (event) => {}, where event is a synthetic touch event as +described above.

onResponderTerminationRequest?: PropTypes.func #

Some other View wants to become responder and is asking this View to release its +responder. Returning true allows its release.

View.props.onResponderTerminationRequest: (event) => {}, where event is a synthetic touch +event as described above.

onStartShouldSetResponder?: PropTypes.func #

Does this view want to become responder on the start of a touch?

View.props.onStartShouldSetResponder: (event) => [true | false], where event is a +synthetic touch event as described above.

onStartShouldSetResponderCapture?: PropTypes.func #

If a parent View wants to prevent a child View from becoming responder on a touch start, +it should have this handler which returns true.

View.props.onStartShouldSetResponderCapture: (event) => [true | false], where event is a +synthetic touch event as described above.

pointerEvents?: PropTypes.oneOf([ + 'box-none', + 'none', + 'box-only', + 'auto', +]) #

Controls whether the View can be the target of touch events.

  • 'auto': The View can be the target of touch events.
  • 'none': The View is never the target of touch events.
  • 'box-none': The View is never the target of touch events but it's +subviews can be. It behaves like if the view had the following classes +in CSS:
    .box-none { + pointer-events: none; +} +.box-none * { + pointer-events: all; +}
  • 'box-only': The view can be the target of touch events but it's +subviews cannot be. It behaves like if the view had the following classes +in CSS:
    .box-only { + pointer-events: all; +} +.box-only * { + pointer-events: none; +}

    Since pointerEvents does not affect layout/appearance, and we are +already deviating from the spec by adding additional modes, we opt to not +include pointerEvents on style. On some platforms, we would need to +implement it as a className anyways. Using style or not is an +implementation detail of the platform.

removeClippedSubviews?: PropTypes.bool #

This is a special performance property exposed by RCTView and is useful +for scrolling content when there are many subviews, most of which are +offscreen. For this property to be effective, it must be applied to a +view that contains many subviews that extend outside its bound. The +subviews must also have overflow: hidden, as should the containing view +(or one of its superviews).

style?: stylePropType #

testID?: PropTypes.string #

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

This disables the 'layout-only view removal' optimization for this view!

androidaccessibilityComponentType?: PropTypes.oneOf(AccessibilityComponentTypes) #

Indicates to accessibility services to treat UI component like a +native one. Works for Android only.

Possible values are one of:

  • 'none'
  • 'button'
  • 'radiobutton_checked'
  • 'radiobutton_unchecked'

androidaccessibilityLiveRegion?: PropTypes.oneOf([ + 'none', + 'polite', + 'assertive', +]) #

Indicates to accessibility services whether the user should be notified +when this view changes. Works for Android API >= 19 only. +Possible values:

  • 'none' - Accessibility services should not announce changes to this view.
  • 'polite'- Accessibility services should announce changes to this view.
  • 'assertive' - Accessibility services should interrupt ongoing speech to immediately announce changes to this view.

See the Android View docs +for reference.

androidcollapsable?: PropTypes.bool #

Views that are only used to layout their children or otherwise don't draw +anything may be automatically removed from the native hierarchy as an +optimization. Set this property to false to disable this optimization and +ensure that this View exists in the native view hierarchy.

androidimportantForAccessibility?: PropTypes.oneOf([ + 'auto', + 'yes', + 'no', + 'no-hide-descendants', +]) #

Controls how view is important for accessibility which is if it +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?: PropTypes.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 +component offscreen and compositing it back with an alpha value. This default +may be noticeable and undesired in the case where the View you are setting +an opacity on has multiple overlapping elements (e.g. multiple overlapping +Views, or text and a background).

Rendering offscreen to preserve correct alpha behavior is extremely +expensive and hard to debug for non-native developers, which is why it is +not turned on by default. If you do need to enable this property for an +animation, consider combining it with renderToHardwareTextureAndroid if the +view contents are static (i.e. it doesn't need to be redrawn each frame). +If that property is enabled, this View will be rendered off-screen once, +saved in a hardware texture, and then composited onto the screen with an alpha +each frame without having to switch rendering targets on the GPU.

androidrenderToHardwareTextureAndroid?: PropTypes.bool #

Whether this View should render itself (and all of its children) into a +single hardware texture on the GPU.

On Android, this is useful for animations and interactions that only +modify opacity, rotation, translation, and/or scale: in those cases, the +view doesn't have to be redrawn and display lists don't need to be +re-executed. The texture can just be re-used and re-composited with +different parameters. The downside is that this can use up limited video +memory, so this prop should be set back to false at the end of the +interaction/animation.

iosaccessibilityTraits?: PropTypes.oneOfType([ + PropTypes.oneOf(AccessibilityTraits), + PropTypes.arrayOf(PropTypes.oneOf(AccessibilityTraits)), +]) #

Provides additional traits to screen reader. By default no traits are +provided unless specified otherwise in element.

You can provide one trait or an array of many traits.

Possible values for AccessibilityTraits are:

  • 'none' - The element has no traits.
  • 'button' - The element should be treated as a button.
  • 'link' - The element should be treated as a link.
  • 'header' - The element is a header that divides content into sections.
  • 'search' - The element should be treated as a search field.
  • 'image' - The element should be treated as an image.
  • 'selected' - The element is selected.
  • 'plays' - The element plays sound.
  • 'key' - The element should be treated like a keyboard key.
  • 'text' - The element should be treated as text.
  • 'summary' - The element provides app summary information.
  • 'disabled' - The element is disabled.
  • 'frequentUpdates' - The element frequently changes its value.
  • 'startsMedia' - The element starts a media session.
  • 'adjustable' - The element allows adjustment over a range of values.
  • 'allowsDirectInteraction' - The element allows direct touch interaction for VoiceOver users.
  • 'pageTurn' - Informs VoiceOver that it should scroll to the next page when it finishes reading the contents of the element.

See the Accessibility guide +for more information.

iosaccessibilityViewIsModal?: PropTypes.bool #

A value indicating whether VoiceOver should ignore the elements +within views that are siblings of the receiver. +Default is false.

See the Accessibility guide +for more information.

iosshouldRasterizeIOS?: PropTypes.bool #

Whether this View should be rendered as a bitmap before compositing.

On iOS, this is useful for animations and interactions that do not +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.

Type Definitions #

Props #

Type:
ViewProps

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

\ No newline at end of file diff --git a/releases/0.47/docs/viewpagerandroid.html b/releases/0.47/docs/viewpagerandroid.html new file mode 100644 index 00000000000..036c603adac --- /dev/null +++ b/releases/0.47/docs/viewpagerandroid.html @@ -0,0 +1,66 @@ +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 +child.

Example:

render: function() { + return ( + <ViewPagerAndroid + style={styles.viewPager} + initialPage={0}> + <View style={styles.pageStyle}> + <Text>First page</Text> + </View> + <View style={styles.pageStyle}> + <Text>Second page</Text> + </View> + </ViewPagerAndroid> + ); +} + +... + +var styles = { + ... + pageStyle: { + alignItems: 'center', + padding: 20, + } +}

Props #

initialPage?: number #

Index of initial page that should be selected. Use setPage method to +update the page, and onPageSelected to monitor page changes

keyboardDismissMode?: literal | literal #

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.

onPageScroll?: Function #

Executed when transitioning between pages (ether because of animation for +the requested page change or when user is swiping/dragging between pages) +The event.nativeEvent object for this callback will carry following data: + - position - index of first page from the left that is currently visible + - offset - value from range [0,1) describing stage between page transitions. + Value x means that (1 - x) fraction of the page at "position" index is + visible, and x fraction of the next page is visible.

onPageScrollStateChanged?: Function #

Function called when the page scrolling state has changed. +The page scrolling state can be in 3 states: +- idle, meaning there is no interaction with the page scroller happening at the time +- dragging, meaning there is currently an interaction with the page scroller +- settling, meaning that there was an interaction with the page scroller, and the + page scroller is now finishing it's closing or opening animation

onPageSelected?: Function #

This callback will be called once ViewPager finish navigating to selected page +(when user swipes between pages). The event.nativeEvent object passed to this +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.

peekEnabled?: boolean #

Whether enable showing peekFraction or not. If this is true, the preview of +last and next page will show in current screen. Defaults to false.

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!

\ No newline at end of file diff --git a/releases/0.47/docs/viewproptypes.html b/releases/0.47/docs/viewproptypes.html new file mode 100644 index 00000000000..36db62bbeb6 --- /dev/null +++ b/releases/0.47/docs/viewproptypes.html @@ -0,0 +1,132 @@ +ViewPropTypes

ViewPropTypes #

Props #

accessibilityLabel?: PropTypes.node #

Overrides the text that's read by the screen reader when the user interacts +with the element. By default, the label is constructed by traversing all the +children and accumulating all the Text nodes separated by space.

accessible?: PropTypes.bool #

When true, indicates that the view is an accessibility element. By default, +all the touchable elements are accessible.

hitSlop?: {top: number, left: number, bottom: number, right: number} #

This defines how far a touch event can start away from the view. +Typical interface guidelines recommend touch targets that are at least +30 - 40 points/density-independent pixels.

For example, if a touchable view has a height of 20 the touchable height can be extended to +40 with hitSlop={{top: 10, bottom: 10, left: 0, right: 0}}

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.

nativeID?: PropTypes.string #

Used to locate this view from native classes.

This disables the 'layout-only view removal' optimization for this view!

onAccessibilityTap?: PropTypes.func #

When accessible is true, the system will try to invoke this function +when the user performs accessibility tap gesture.

onLayout?: PropTypes.func #

Invoked on mount and layout changes with:

{nativeEvent: { layout: {x, y, width, height}}}

This event is fired immediately once the layout has been calculated, but +the new layout may not yet be reflected on the screen at the time the +event is received, especially if a layout animation is in progress.

onMagicTap?: PropTypes.func #

When accessible is true, the system will invoke this function when the +user performs the magic tap gesture.

onMoveShouldSetResponder?: PropTypes.func #

Does this view want to "claim" touch responsiveness? This is called for every touch move on +the View when it is not the responder.

View.props.onMoveShouldSetResponder: (event) => [true | false], where event is a +synthetic touch event as described above.

onMoveShouldSetResponderCapture?: PropTypes.func #

If a parent View wants to prevent a child View from becoming responder on a move, +it should have this handler which returns true.

View.props.onMoveShouldSetResponderCapture: (event) => [true | false], where event is a +synthetic touch event as described above.

onResponderGrant?: PropTypes.func #

The View is now responding for touch events. This is the time to highlight and show the user +what is happening.

View.props.onResponderGrant: (event) => {}, where event is a synthetic touch event as +described above.

onResponderMove?: PropTypes.func #

The user is moving their finger.

View.props.onResponderMove: (event) => {}, where event is a synthetic touch event as +described above.

onResponderReject?: PropTypes.func #

Another responder is already active and will not release it to that View asking to be +the responder.

View.props.onResponderReject: (event) => {}, where event is a synthetic touch event as +described above.

onResponderRelease?: PropTypes.func #

Fired at the end of the touch.

View.props.onResponderRelease: (event) => {}, where event is a synthetic touch event as +described above.

onResponderTerminate?: PropTypes.func #

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 (e.g., happens +with control center/ notification center on iOS)

View.props.onResponderTerminate: (event) => {}, where event is a synthetic touch event as +described above.

onResponderTerminationRequest?: PropTypes.func #

Some other View wants to become responder and is asking this View to release its +responder. Returning true allows its release.

View.props.onResponderTerminationRequest: (event) => {}, where event is a synthetic touch +event as described above.

onStartShouldSetResponder?: PropTypes.func #

Does this view want to become responder on the start of a touch?

View.props.onStartShouldSetResponder: (event) => [true | false], where event is a +synthetic touch event as described above.

onStartShouldSetResponderCapture?: PropTypes.func #

If a parent View wants to prevent a child View from becoming responder on a touch start, +it should have this handler which returns true.

View.props.onStartShouldSetResponderCapture: (event) => [true | false], where event is a +synthetic touch event as described above.

pointerEvents?: PropTypes.oneOf([ + 'box-none', + 'none', + 'box-only', + 'auto', +]) #

Controls whether the View can be the target of touch events.

  • 'auto': The View can be the target of touch events.
  • 'none': The View is never the target of touch events.
  • 'box-none': The View is never the target of touch events but it's +subviews can be. It behaves like if the view had the following classes +in CSS:
    .box-none { + pointer-events: none; +} +.box-none * { + pointer-events: all; +}
  • 'box-only': The view can be the target of touch events but it's +subviews cannot be. It behaves like if the view had the following classes +in CSS:
    .box-only { + pointer-events: all; +} +.box-only * { + pointer-events: none; +}

    Since pointerEvents does not affect layout/appearance, and we are +already deviating from the spec by adding additional modes, we opt to not +include pointerEvents on style. On some platforms, we would need to +implement it as a className anyways. Using style or not is an +implementation detail of the platform.

removeClippedSubviews?: PropTypes.bool #

This is a special performance property exposed by RCTView and is useful +for scrolling content when there are many subviews, most of which are +offscreen. For this property to be effective, it must be applied to a +view that contains many subviews that extend outside its bound. The +subviews must also have overflow: hidden, as should the containing view +(or one of its superviews).

style?: stylePropType #

testID?: PropTypes.string #

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

This disables the 'layout-only view removal' optimization for this view!

androidaccessibilityComponentType?: PropTypes.oneOf(AccessibilityComponentTypes) #

Indicates to accessibility services to treat UI component like a +native one. Works for Android only.

Possible values are one of:

  • 'none'
  • 'button'
  • 'radiobutton_checked'
  • 'radiobutton_unchecked'

androidaccessibilityLiveRegion?: PropTypes.oneOf([ + 'none', + 'polite', + 'assertive', +]) #

Indicates to accessibility services whether the user should be notified +when this view changes. Works for Android API >= 19 only. +Possible values:

  • 'none' - Accessibility services should not announce changes to this view.
  • 'polite'- Accessibility services should announce changes to this view.
  • 'assertive' - Accessibility services should interrupt ongoing speech to immediately announce changes to this view.

See the Android View docs +for reference.

androidcollapsable?: PropTypes.bool #

Views that are only used to layout their children or otherwise don't draw +anything may be automatically removed from the native hierarchy as an +optimization. Set this property to false to disable this optimization and +ensure that this View exists in the native view hierarchy.

androidimportantForAccessibility?: PropTypes.oneOf([ + 'auto', + 'yes', + 'no', + 'no-hide-descendants', +]) #

Controls how view is important for accessibility which is if it +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?: PropTypes.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 +component offscreen and compositing it back with an alpha value. This default +may be noticeable and undesired in the case where the View you are setting +an opacity on has multiple overlapping elements (e.g. multiple overlapping +Views, or text and a background).

Rendering offscreen to preserve correct alpha behavior is extremely +expensive and hard to debug for non-native developers, which is why it is +not turned on by default. If you do need to enable this property for an +animation, consider combining it with renderToHardwareTextureAndroid if the +view contents are static (i.e. it doesn't need to be redrawn each frame). +If that property is enabled, this View will be rendered off-screen once, +saved in a hardware texture, and then composited onto the screen with an alpha +each frame without having to switch rendering targets on the GPU.

androidrenderToHardwareTextureAndroid?: PropTypes.bool #

Whether this View should render itself (and all of its children) into a +single hardware texture on the GPU.

On Android, this is useful for animations and interactions that only +modify opacity, rotation, translation, and/or scale: in those cases, the +view doesn't have to be redrawn and display lists don't need to be +re-executed. The texture can just be re-used and re-composited with +different parameters. The downside is that this can use up limited video +memory, so this prop should be set back to false at the end of the +interaction/animation.

iosaccessibilityTraits?: PropTypes.oneOfType([ + PropTypes.oneOf(AccessibilityTraits), + PropTypes.arrayOf(PropTypes.oneOf(AccessibilityTraits)), +]) #

Provides additional traits to screen reader. By default no traits are +provided unless specified otherwise in element.

You can provide one trait or an array of many traits.

Possible values for AccessibilityTraits are:

  • 'none' - The element has no traits.
  • 'button' - The element should be treated as a button.
  • 'link' - The element should be treated as a link.
  • 'header' - The element is a header that divides content into sections.
  • 'search' - The element should be treated as a search field.
  • 'image' - The element should be treated as an image.
  • 'selected' - The element is selected.
  • 'plays' - The element plays sound.
  • 'key' - The element should be treated like a keyboard key.
  • 'text' - The element should be treated as text.
  • 'summary' - The element provides app summary information.
  • 'disabled' - The element is disabled.
  • 'frequentUpdates' - The element frequently changes its value.
  • 'startsMedia' - The element starts a media session.
  • 'adjustable' - The element allows adjustment over a range of values.
  • 'allowsDirectInteraction' - The element allows direct touch interaction for VoiceOver users.
  • 'pageTurn' - Informs VoiceOver that it should scroll to the next page when it finishes reading the contents of the element.

See the Accessibility guide +for more information.

iosaccessibilityViewIsModal?: PropTypes.bool #

A value indicating whether VoiceOver should ignore the elements +within views that are siblings of the receiver. +Default is false.

See the Accessibility guide +for more information.

iosshouldRasterizeIOS?: PropTypes.bool #

Whether this View should be rendered as a bitmap before compositing.

On iOS, this is useful for animations and interactions that do not +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!

\ No newline at end of file diff --git a/releases/0.47/docs/viewstyleproptypes.html b/releases/0.47/docs/viewstyleproptypes.html new file mode 100644 index 00000000000..4df739eea8d --- /dev/null +++ b/releases/0.47/docs/viewstyleproptypes.html @@ -0,0 +1,22 @@ +ViewStylePropTypes

ViewStylePropTypes #

Props #

backfaceVisibility?: ReactPropTypes.oneOf(['visible', 'hidden']) #

backgroundColor?: color #

borderBottomColor?: color #

borderBottomLeftRadius?: ReactPropTypes.number #

borderBottomRightRadius?: ReactPropTypes.number #

borderBottomWidth?: ReactPropTypes.number #

borderColor?: color #

borderLeftColor?: color #

borderLeftWidth?: ReactPropTypes.number #

borderRadius?: ReactPropTypes.number #

borderRightColor?: color #

borderRightWidth?: ReactPropTypes.number #

borderStyle?: ReactPropTypes.oneOf(['solid', 'dotted', 'dashed']) #

borderTopColor?: color #

borderTopLeftRadius?: ReactPropTypes.number #

borderTopRightRadius?: ReactPropTypes.number #

borderTopWidth?: ReactPropTypes.number #

borderWidth?: ReactPropTypes.number #

opacity?: ReactPropTypes.number #

androidelevation?: ReactPropTypes.number #

(Android-only) Sets the elevation of a view, using Android's underlying +elevation API. +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.

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

\ No newline at end of file diff --git a/releases/0.47/docs/virtualizedlist.html b/releases/0.47/docs/virtualizedlist.html new file mode 100644 index 00000000000..79a6bd7f27f --- /dev/null +++ b/releases/0.47/docs/virtualizedlist.html @@ -0,0 +1,66 @@ +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 +maintaining a finite render window of active items and replacing all items outside of the render +window with appropriately sized blank space. The window adapts to scrolling behavior, and items +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 +(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 #

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 +this for debugging purposes.

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: (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.

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.

inverted?: ?boolean #

Reverses the direction of scroll. Uses scale transforms of -1.

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 #

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 +this number will reduce memory consumption and may improve performance, but will increase the +chance that fast scrolling may reveal momentary blank areas of unrendered content.

androidprogressViewOffset?: number #

Set this when offset is needed for the loading indicator to show correctly.

Methods #

scrollToEnd(params?: object) #

scrollToIndex(params: object) #

scrollToItem(params: object) #

scrollToOffset(params: object) #

Scroll to a specific content pixel offset in the list.

Param offset expects the offset to scroll to. +In case of horizontal is true, the offset is the x-value, +in any other case the offset is the y-value.

Param animated (true by default) defines whether the list +should do an animation while scrolling.

recordInteraction() #

flashScrollIndicators() #

Type Definitions #

Props #

Type:
IntersectionTypeAnnotation

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

\ No newline at end of file diff --git a/releases/0.47/docs/webview.html b/releases/0.47/docs/webview.html new file mode 100644 index 00000000000..e6b526cc394 --- /dev/null +++ b/releases/0.47/docs/webview.html @@ -0,0 +1,106 @@ +WebView

WebView #

WebView renders web content in a native view.

import React, { Component } from 'react'; +import { WebView } from 'react-native'; + +class MyWeb extends Component { + render() { + return ( + <WebView + source={{uri: 'https://github.com/facebook/react-native'}} + style={{marginTop: 20}} + /> + ); + } +}

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?: 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?: 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?: 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?: 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.

androidthirdPartyCookiesEnabled?: PropTypes.bool #

Boolean value to enable third party cookies in the WebView. Used on +Android Lollipop and above only as third party cookies are enabled by +default on Android Kitkat and below and on iOS. The default value is true.

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?: 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?: 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?: PropTypes.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!

\ No newline at end of file diff --git a/releases/0.47/img/AVDManagerMacOS.png b/releases/0.47/img/AVDManagerMacOS.png new file mode 100644 index 00000000000..298d9f4db25 Binary files /dev/null and b/releases/0.47/img/AVDManagerMacOS.png differ diff --git a/releases/0.47/img/AVDManagerWindows.png b/releases/0.47/img/AVDManagerWindows.png new file mode 100644 index 00000000000..15706357464 Binary files /dev/null and b/releases/0.47/img/AVDManagerWindows.png differ diff --git a/releases/0.47/img/AddToBuildPhases.png b/releases/0.47/img/AddToBuildPhases.png new file mode 100644 index 00000000000..7b83937020d Binary files /dev/null and b/releases/0.47/img/AddToBuildPhases.png differ diff --git a/releases/0.47/img/AddToLibraries.png b/releases/0.47/img/AddToLibraries.png new file mode 100644 index 00000000000..652cdfd1cfd Binary files /dev/null and b/releases/0.47/img/AddToLibraries.png differ diff --git a/releases/0.47/img/AddToSearchPaths.png b/releases/0.47/img/AddToSearchPaths.png new file mode 100644 index 00000000000..ccbe819ba78 Binary files /dev/null and b/releases/0.47/img/AddToSearchPaths.png differ diff --git a/releases/0.47/img/AdministratorCommandPrompt.png b/releases/0.47/img/AdministratorCommandPrompt.png new file mode 100644 index 00000000000..99345236bd3 Binary files /dev/null and b/releases/0.47/img/AdministratorCommandPrompt.png differ diff --git a/releases/0.47/img/AndroidAVDConfiguration.png b/releases/0.47/img/AndroidAVDConfiguration.png new file mode 100644 index 00000000000..ef5e3e8b25c Binary files /dev/null and b/releases/0.47/img/AndroidAVDConfiguration.png differ diff --git a/releases/0.47/img/AndroidDevServerDialog.png b/releases/0.47/img/AndroidDevServerDialog.png new file mode 100644 index 00000000000..9fd5536acdf Binary files /dev/null and b/releases/0.47/img/AndroidDevServerDialog.png differ diff --git a/releases/0.47/img/AndroidDevSettings.png b/releases/0.47/img/AndroidDevSettings.png new file mode 100644 index 00000000000..0c214571f7e Binary files /dev/null and b/releases/0.47/img/AndroidDevSettings.png differ diff --git a/releases/0.47/img/AndroidDeveloperMenu.png b/releases/0.47/img/AndroidDeveloperMenu.png new file mode 100644 index 00000000000..2fae4ccaa23 Binary files /dev/null and b/releases/0.47/img/AndroidDeveloperMenu.png differ diff --git a/releases/0.47/img/AndroidEnvironmentVariableANDROID_HOME.png b/releases/0.47/img/AndroidEnvironmentVariableANDROID_HOME.png new file mode 100644 index 00000000000..1e6d35caa6a Binary files /dev/null and b/releases/0.47/img/AndroidEnvironmentVariableANDROID_HOME.png differ diff --git a/releases/0.47/img/AndroidSDK1.png b/releases/0.47/img/AndroidSDK1.png new file mode 100644 index 00000000000..9b9add740ed Binary files /dev/null and b/releases/0.47/img/AndroidSDK1.png differ diff --git a/releases/0.47/img/AndroidSDK2.png b/releases/0.47/img/AndroidSDK2.png new file mode 100644 index 00000000000..a554e07d48e Binary files /dev/null and b/releases/0.47/img/AndroidSDK2.png differ diff --git a/releases/0.47/img/AndroidSDKManagerInstallsMacOS.png b/releases/0.47/img/AndroidSDKManagerInstallsMacOS.png new file mode 100644 index 00000000000..c93b57a6051 Binary files /dev/null and b/releases/0.47/img/AndroidSDKManagerInstallsMacOS.png differ diff --git a/releases/0.47/img/AndroidSDKManagerInstallsWindows.png b/releases/0.47/img/AndroidSDKManagerInstallsWindows.png new file mode 100644 index 00000000000..e0e4deb7f99 Binary files /dev/null and b/releases/0.47/img/AndroidSDKManagerInstallsWindows.png differ diff --git a/releases/0.47/img/AndroidSDKManagerMacOS.png b/releases/0.47/img/AndroidSDKManagerMacOS.png new file mode 100644 index 00000000000..8d0a8f3bb9f Binary files /dev/null and b/releases/0.47/img/AndroidSDKManagerMacOS.png differ diff --git a/releases/0.47/img/AndroidSDKManagerSDKToolsMacOS.png b/releases/0.47/img/AndroidSDKManagerSDKToolsMacOS.png new file mode 100644 index 00000000000..44f002b5483 Binary files /dev/null and b/releases/0.47/img/AndroidSDKManagerSDKToolsMacOS.png differ diff --git a/releases/0.47/img/AndroidSDKManagerSDKToolsWindows.png b/releases/0.47/img/AndroidSDKManagerSDKToolsWindows.png new file mode 100644 index 00000000000..5ea04a60483 Binary files /dev/null and b/releases/0.47/img/AndroidSDKManagerSDKToolsWindows.png differ diff --git a/releases/0.47/img/AndroidSDKManagerWindows.png b/releases/0.47/img/AndroidSDKManagerWindows.png new file mode 100644 index 00000000000..fe78e2a2f45 Binary files /dev/null and b/releases/0.47/img/AndroidSDKManagerWindows.png differ diff --git a/releases/0.47/img/AndroidStudioCustomSetup.png b/releases/0.47/img/AndroidStudioCustomSetup.png new file mode 100644 index 00000000000..4d7e16b6fd5 Binary files /dev/null and b/releases/0.47/img/AndroidStudioCustomSetup.png differ diff --git a/releases/0.47/img/AndroidStudioWelcomeMacOS.png b/releases/0.47/img/AndroidStudioWelcomeMacOS.png new file mode 100644 index 00000000000..3ba178525ab Binary files /dev/null and b/releases/0.47/img/AndroidStudioWelcomeMacOS.png differ diff --git a/releases/0.47/img/AndroidStudioWelcomeWindows.png b/releases/0.47/img/AndroidStudioWelcomeWindows.png new file mode 100644 index 00000000000..e65229bd927 Binary files /dev/null and b/releases/0.47/img/AndroidStudioWelcomeWindows.png differ diff --git a/releases/0.47/img/AndroidSuccessMacOS.png b/releases/0.47/img/AndroidSuccessMacOS.png new file mode 100644 index 00000000000..0fbb4e9f832 Binary files /dev/null and b/releases/0.47/img/AndroidSuccessMacOS.png differ diff --git a/releases/0.47/img/AndroidSuccessWindows.png b/releases/0.47/img/AndroidSuccessWindows.png new file mode 100644 index 00000000000..4c653bae64f Binary files /dev/null and b/releases/0.47/img/AndroidSuccessWindows.png differ diff --git a/releases/0.47/img/AnimatedFadeInView.gif b/releases/0.47/img/AnimatedFadeInView.gif new file mode 100644 index 00000000000..d0d02a1a2ab Binary files /dev/null and b/releases/0.47/img/AnimatedFadeInView.gif differ diff --git a/releases/0.47/img/AnimationExperimentalOpacity.gif b/releases/0.47/img/AnimationExperimentalOpacity.gif new file mode 100644 index 00000000000..cdc79022b7e Binary files /dev/null and b/releases/0.47/img/AnimationExperimentalOpacity.gif differ diff --git a/releases/0.47/img/AnimationExperimentalScaleXY.gif b/releases/0.47/img/AnimationExperimentalScaleXY.gif new file mode 100644 index 00000000000..850cfd18c2b Binary files /dev/null and b/releases/0.47/img/AnimationExperimentalScaleXY.gif differ diff --git a/releases/0.47/img/Button.png b/releases/0.47/img/Button.png new file mode 100644 index 00000000000..3158460edb2 Binary files /dev/null and b/releases/0.47/img/Button.png differ diff --git a/releases/0.47/img/ConfigureReleaseScheme.png b/releases/0.47/img/ConfigureReleaseScheme.png new file mode 100644 index 00000000000..dd671cc8391 Binary files /dev/null and b/releases/0.47/img/ConfigureReleaseScheme.png differ diff --git a/releases/0.47/img/CreateAVDMacOS.png b/releases/0.47/img/CreateAVDMacOS.png new file mode 100644 index 00000000000..ee922502962 Binary files /dev/null and b/releases/0.47/img/CreateAVDMacOS.png differ diff --git a/releases/0.47/img/CreateAVDWindows.png b/releases/0.47/img/CreateAVDWindows.png new file mode 100644 index 00000000000..545663f7f17 Binary files /dev/null and b/releases/0.47/img/CreateAVDWindows.png differ diff --git a/releases/0.47/img/CreateAVDx86MacOS.png b/releases/0.47/img/CreateAVDx86MacOS.png new file mode 100644 index 00000000000..c1ca88aac03 Binary files /dev/null and b/releases/0.47/img/CreateAVDx86MacOS.png differ diff --git a/releases/0.47/img/CreateAVDx86Windows.png b/releases/0.47/img/CreateAVDx86Windows.png new file mode 100644 index 00000000000..681daade763 Binary files /dev/null and b/releases/0.47/img/CreateAVDx86Windows.png differ diff --git a/releases/0.47/img/DeveloperMenu.png b/releases/0.47/img/DeveloperMenu.png new file mode 100644 index 00000000000..bb295444ee1 Binary files /dev/null and b/releases/0.47/img/DeveloperMenu.png differ diff --git a/releases/0.47/img/EmbeddedAppAndroid.png b/releases/0.47/img/EmbeddedAppAndroid.png new file mode 100644 index 00000000000..126ba2d7442 Binary files /dev/null and b/releases/0.47/img/EmbeddedAppAndroid.png differ diff --git a/releases/0.47/img/EmbeddedAppContainerViewExample.png b/releases/0.47/img/EmbeddedAppContainerViewExample.png new file mode 100644 index 00000000000..6130dfb1e10 Binary files /dev/null and b/releases/0.47/img/EmbeddedAppContainerViewExample.png differ diff --git a/releases/0.47/img/EmbeddedAppExample.png b/releases/0.47/img/EmbeddedAppExample.png new file mode 100644 index 00000000000..fefd3069ddf Binary files /dev/null and b/releases/0.47/img/EmbeddedAppExample.png differ diff --git a/releases/0.47/img/Inspector.gif b/releases/0.47/img/Inspector.gif new file mode 100644 index 00000000000..b7589733c82 Binary files /dev/null and b/releases/0.47/img/Inspector.gif differ diff --git a/releases/0.47/img/LayoutAnimationExample.gif b/releases/0.47/img/LayoutAnimationExample.gif new file mode 100644 index 00000000000..68fcfcee4d7 Binary files /dev/null and b/releases/0.47/img/LayoutAnimationExample.gif differ diff --git a/releases/0.47/img/NavigationStack-Navigator.gif b/releases/0.47/img/NavigationStack-Navigator.gif new file mode 100644 index 00000000000..c1f8313996c Binary files /dev/null and b/releases/0.47/img/NavigationStack-Navigator.gif differ diff --git a/releases/0.47/img/NavigationStack-NavigatorIOS.gif b/releases/0.47/img/NavigationStack-NavigatorIOS.gif new file mode 100644 index 00000000000..c1d56a1f555 Binary files /dev/null and b/releases/0.47/img/NavigationStack-NavigatorIOS.gif differ diff --git a/releases/0.47/img/ObjectObserveError.png b/releases/0.47/img/ObjectObserveError.png new file mode 100644 index 00000000000..3634969fdfc Binary files /dev/null and b/releases/0.47/img/ObjectObserveError.png differ diff --git a/releases/0.47/img/PerfUtil.png b/releases/0.47/img/PerfUtil.png new file mode 100644 index 00000000000..187f114f783 Binary files /dev/null and b/releases/0.47/img/PerfUtil.png differ diff --git a/releases/0.47/img/ReactDevTools.png b/releases/0.47/img/ReactDevTools.png new file mode 100644 index 00000000000..caa3af713b3 Binary files /dev/null and b/releases/0.47/img/ReactDevTools.png differ diff --git a/releases/0.47/img/ReactDevToolsDollarR.gif b/releases/0.47/img/ReactDevToolsDollarR.gif new file mode 100644 index 00000000000..373d80b90a9 Binary files /dev/null and b/releases/0.47/img/ReactDevToolsDollarR.gif differ diff --git a/releases/0.47/img/ReactDevToolsInspector.gif b/releases/0.47/img/ReactDevToolsInspector.gif new file mode 100644 index 00000000000..c3540bee79c Binary files /dev/null and b/releases/0.47/img/ReactDevToolsInspector.gif differ diff --git a/releases/0.47/img/Rebound.gif b/releases/0.47/img/Rebound.gif new file mode 100644 index 00000000000..03716633818 Binary files /dev/null and b/releases/0.47/img/Rebound.gif differ diff --git a/releases/0.47/img/ReboundExample.png b/releases/0.47/img/ReboundExample.png new file mode 100644 index 00000000000..db33e5f8a85 Binary files /dev/null and b/releases/0.47/img/ReboundExample.png differ diff --git a/releases/0.47/img/ReboundImage.gif b/releases/0.47/img/ReboundImage.gif new file mode 100644 index 00000000000..9c1da74f150 Binary files /dev/null and b/releases/0.47/img/ReboundImage.gif differ diff --git a/releases/0.47/img/RunningOnDeviceCodeSigning.png b/releases/0.47/img/RunningOnDeviceCodeSigning.png new file mode 100644 index 00000000000..8bf01d61e7f Binary files /dev/null and b/releases/0.47/img/RunningOnDeviceCodeSigning.png differ diff --git a/releases/0.47/img/RunningOnDeviceReady.png b/releases/0.47/img/RunningOnDeviceReady.png new file mode 100644 index 00000000000..e251d1663bd Binary files /dev/null and b/releases/0.47/img/RunningOnDeviceReady.png differ diff --git a/releases/0.47/img/StaticImageAssets.png b/releases/0.47/img/StaticImageAssets.png new file mode 100644 index 00000000000..e79acdc1b6f Binary files /dev/null and b/releases/0.47/img/StaticImageAssets.png differ diff --git a/releases/0.47/img/SystraceBadCreateUI.png b/releases/0.47/img/SystraceBadCreateUI.png new file mode 100644 index 00000000000..813b1014aea Binary files /dev/null and b/releases/0.47/img/SystraceBadCreateUI.png differ diff --git a/releases/0.47/img/SystraceBadJS.png b/releases/0.47/img/SystraceBadJS.png new file mode 100644 index 00000000000..c67c840ac92 Binary files /dev/null and b/releases/0.47/img/SystraceBadJS.png differ diff --git a/releases/0.47/img/SystraceBadJS2.png b/releases/0.47/img/SystraceBadJS2.png new file mode 100644 index 00000000000..de972c6494a Binary files /dev/null and b/releases/0.47/img/SystraceBadJS2.png differ diff --git a/releases/0.47/img/SystraceBadUI.png b/releases/0.47/img/SystraceBadUI.png new file mode 100644 index 00000000000..ebd9faf7d66 Binary files /dev/null and b/releases/0.47/img/SystraceBadUI.png differ diff --git a/releases/0.47/img/SystraceExample.png b/releases/0.47/img/SystraceExample.png new file mode 100644 index 00000000000..521ee1635c8 Binary files /dev/null and b/releases/0.47/img/SystraceExample.png differ diff --git a/releases/0.47/img/SystraceHighlightVSync.png b/releases/0.47/img/SystraceHighlightVSync.png new file mode 100644 index 00000000000..dc7595a3611 Binary files /dev/null and b/releases/0.47/img/SystraceHighlightVSync.png differ diff --git a/releases/0.47/img/SystraceJSThreadExample.png b/releases/0.47/img/SystraceJSThreadExample.png new file mode 100644 index 00000000000..736af7d0562 Binary files /dev/null and b/releases/0.47/img/SystraceJSThreadExample.png differ diff --git a/releases/0.47/img/SystraceNativeModulesThreadExample.png b/releases/0.47/img/SystraceNativeModulesThreadExample.png new file mode 100644 index 00000000000..7e919f24c22 Binary files /dev/null and b/releases/0.47/img/SystraceNativeModulesThreadExample.png differ diff --git a/releases/0.47/img/SystraceRenderThreadExample.png b/releases/0.47/img/SystraceRenderThreadExample.png new file mode 100644 index 00000000000..2fa05bdbddd Binary files /dev/null and b/releases/0.47/img/SystraceRenderThreadExample.png differ diff --git a/releases/0.47/img/SystraceUIThreadExample.png b/releases/0.47/img/SystraceUIThreadExample.png new file mode 100644 index 00000000000..4883e85c075 Binary files /dev/null and b/releases/0.47/img/SystraceUIThreadExample.png differ diff --git a/releases/0.47/img/SystraceWellBehaved.png b/releases/0.47/img/SystraceWellBehaved.png new file mode 100644 index 00000000000..95408738f74 Binary files /dev/null and b/releases/0.47/img/SystraceWellBehaved.png differ diff --git a/releases/0.47/img/TutorialFinal.png b/releases/0.47/img/TutorialFinal.png new file mode 100644 index 00000000000..2f05b13e2ea Binary files /dev/null and b/releases/0.47/img/TutorialFinal.png differ diff --git a/releases/0.47/img/TutorialFinal2.png b/releases/0.47/img/TutorialFinal2.png new file mode 100644 index 00000000000..75ec47c54ea Binary files /dev/null and b/releases/0.47/img/TutorialFinal2.png differ diff --git a/releases/0.47/img/TutorialMock.png b/releases/0.47/img/TutorialMock.png new file mode 100644 index 00000000000..6a267d08995 Binary files /dev/null and b/releases/0.47/img/TutorialMock.png differ diff --git a/releases/0.47/img/TutorialMock2.png b/releases/0.47/img/TutorialMock2.png new file mode 100644 index 00000000000..94c7f656b1d Binary files /dev/null and b/releases/0.47/img/TutorialMock2.png differ diff --git a/releases/0.47/img/TutorialSingleFetched.png b/releases/0.47/img/TutorialSingleFetched.png new file mode 100644 index 00000000000..914cb8833b9 Binary files /dev/null and b/releases/0.47/img/TutorialSingleFetched.png differ diff --git a/releases/0.47/img/TutorialSingleFetched2.png b/releases/0.47/img/TutorialSingleFetched2.png new file mode 100644 index 00000000000..c7dfd69e8d3 Binary files /dev/null and b/releases/0.47/img/TutorialSingleFetched2.png differ diff --git a/releases/0.47/img/TutorialStyledMock.png b/releases/0.47/img/TutorialStyledMock.png new file mode 100644 index 00000000000..48fb1c5e732 Binary files /dev/null and b/releases/0.47/img/TutorialStyledMock.png differ diff --git a/releases/0.47/img/TutorialStyledMock2.png b/releases/0.47/img/TutorialStyledMock2.png new file mode 100644 index 00000000000..16e99c2028f Binary files /dev/null and b/releases/0.47/img/TutorialStyledMock2.png differ diff --git a/releases/0.47/img/TweenState.gif b/releases/0.47/img/TweenState.gif new file mode 100644 index 00000000000..84f34d2ec8f Binary files /dev/null and b/releases/0.47/img/TweenState.gif differ diff --git a/releases/0.47/img/Warning.png b/releases/0.47/img/Warning.png new file mode 100644 index 00000000000..ceeb6edf2c6 Binary files /dev/null and b/releases/0.47/img/Warning.png differ diff --git a/releases/0.47/img/XcodeCommandLineTools.png b/releases/0.47/img/XcodeCommandLineTools.png new file mode 100644 index 00000000000..e19d3a9f794 Binary files /dev/null and b/releases/0.47/img/XcodeCommandLineTools.png differ diff --git a/releases/0.47/img/alertIOS.png b/releases/0.47/img/alertIOS.png new file mode 100644 index 00000000000..b35a2a457f9 Binary files /dev/null and b/releases/0.47/img/alertIOS.png differ diff --git a/releases/0.47/img/author.png b/releases/0.47/img/author.png new file mode 100644 index 00000000000..deff4c45562 Binary files /dev/null and b/releases/0.47/img/author.png differ diff --git a/releases/0.47/img/buttonExample.png b/releases/0.47/img/buttonExample.png new file mode 100644 index 00000000000..40ce923b45b Binary files /dev/null and b/releases/0.47/img/buttonExample.png differ diff --git a/releases/0.47/img/chrome_breakpoint.png b/releases/0.47/img/chrome_breakpoint.png new file mode 100644 index 00000000000..d37c9538b03 Binary files /dev/null and b/releases/0.47/img/chrome_breakpoint.png differ diff --git a/releases/0.47/img/favicon.png b/releases/0.47/img/favicon.png new file mode 100644 index 00000000000..22c120d09b2 Binary files /dev/null and b/releases/0.47/img/favicon.png differ diff --git a/releases/0.47/img/header_logo.png b/releases/0.47/img/header_logo.png new file mode 100644 index 00000000000..8858ffa29da Binary files /dev/null and b/releases/0.47/img/header_logo.png differ diff --git a/releases/0.47/img/iOSSuccess.png b/releases/0.47/img/iOSSuccess.png new file mode 100644 index 00000000000..457824f4ee5 Binary files /dev/null and b/releases/0.47/img/iOSSuccess.png differ diff --git a/releases/0.47/img/opengraph.png b/releases/0.47/img/opengraph.png new file mode 100644 index 00000000000..437433e9afa Binary files /dev/null and b/releases/0.47/img/opengraph.png differ diff --git a/releases/0.47/img/oss_logo.png b/releases/0.47/img/oss_logo.png new file mode 100644 index 00000000000..8183e289b13 Binary files /dev/null and b/releases/0.47/img/oss_logo.png differ diff --git a/releases/0.47/img/react-native-add-react-native-integration-example-high-scores.png b/releases/0.47/img/react-native-add-react-native-integration-example-high-scores.png new file mode 100644 index 00000000000..6d07707ba86 Binary files /dev/null and b/releases/0.47/img/react-native-add-react-native-integration-example-high-scores.png differ diff --git a/releases/0.47/img/react-native-add-react-native-integration-example-home-screen.png b/releases/0.47/img/react-native-add-react-native-integration-example-home-screen.png new file mode 100644 index 00000000000..2b1b8b28735 Binary files /dev/null and b/releases/0.47/img/react-native-add-react-native-integration-example-home-screen.png differ diff --git a/releases/0.47/img/react-native-add-react-native-integration-link.png b/releases/0.47/img/react-native-add-react-native-integration-link.png new file mode 100644 index 00000000000..3d89eaf020a Binary files /dev/null and b/releases/0.47/img/react-native-add-react-native-integration-link.png differ diff --git a/releases/0.47/img/react-native-add-react-native-integration-wire-up.png b/releases/0.47/img/react-native-add-react-native-integration-wire-up.png new file mode 100644 index 00000000000..43d2add57ba Binary files /dev/null and b/releases/0.47/img/react-native-add-react-native-integration-wire-up.png differ diff --git a/releases/0.47/img/react-native-android-studio-additional-installs-linux.png b/releases/0.47/img/react-native-android-studio-additional-installs-linux.png new file mode 100644 index 00000000000..3a0eda555b5 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-additional-installs-linux.png differ diff --git a/releases/0.47/img/react-native-android-studio-additional-installs.png b/releases/0.47/img/react-native-android-studio-additional-installs.png new file mode 100644 index 00000000000..de32a09e007 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-additional-installs.png differ diff --git a/releases/0.47/img/react-native-android-studio-android-sdk-build-tools-linux.png b/releases/0.47/img/react-native-android-studio-android-sdk-build-tools-linux.png new file mode 100644 index 00000000000..10391c74108 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-android-sdk-build-tools-linux.png differ diff --git a/releases/0.47/img/react-native-android-studio-android-sdk-build-tools-windows.png b/releases/0.47/img/react-native-android-studio-android-sdk-build-tools-windows.png new file mode 100644 index 00000000000..600ef3a428a Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-android-sdk-build-tools-windows.png differ diff --git a/releases/0.47/img/react-native-android-studio-android-sdk-build-tools.png b/releases/0.47/img/react-native-android-studio-android-sdk-build-tools.png new file mode 100644 index 00000000000..a1d80be7a57 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-android-sdk-build-tools.png differ diff --git a/releases/0.47/img/react-native-android-studio-android-sdk-platforms-linux.png b/releases/0.47/img/react-native-android-studio-android-sdk-platforms-linux.png new file mode 100644 index 00000000000..8c43a493867 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-android-sdk-platforms-linux.png differ diff --git a/releases/0.47/img/react-native-android-studio-android-sdk-platforms-windows.png b/releases/0.47/img/react-native-android-studio-android-sdk-platforms-windows.png new file mode 100644 index 00000000000..a5cf1758d28 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-android-sdk-platforms-windows.png differ diff --git a/releases/0.47/img/react-native-android-studio-android-sdk-platforms.png b/releases/0.47/img/react-native-android-studio-android-sdk-platforms.png new file mode 100644 index 00000000000..34407b136d6 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-android-sdk-platforms.png differ diff --git a/releases/0.47/img/react-native-android-studio-avd-linux.png b/releases/0.47/img/react-native-android-studio-avd-linux.png new file mode 100644 index 00000000000..de5f2542095 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-avd-linux.png differ diff --git a/releases/0.47/img/react-native-android-studio-avd-windows.png b/releases/0.47/img/react-native-android-studio-avd-windows.png new file mode 100644 index 00000000000..ddc8f4790a7 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-avd-windows.png differ diff --git a/releases/0.47/img/react-native-android-studio-avd.png b/releases/0.47/img/react-native-android-studio-avd.png new file mode 100644 index 00000000000..74c053b6cf9 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-avd.png differ diff --git a/releases/0.47/img/react-native-android-studio-configure-sdk-linux.png b/releases/0.47/img/react-native-android-studio-configure-sdk-linux.png new file mode 100644 index 00000000000..8bb9d5fea6f Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-configure-sdk-linux.png differ diff --git a/releases/0.47/img/react-native-android-studio-configure-sdk-windows.png b/releases/0.47/img/react-native-android-studio-configure-sdk-windows.png new file mode 100644 index 00000000000..1adf5cbdb80 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-configure-sdk-windows.png differ diff --git a/releases/0.47/img/react-native-android-studio-configure-sdk.png b/releases/0.47/img/react-native-android-studio-configure-sdk.png new file mode 100644 index 00000000000..acfe1f30c8c Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-configure-sdk.png differ diff --git a/releases/0.47/img/react-native-android-studio-custom-install-linux.png b/releases/0.47/img/react-native-android-studio-custom-install-linux.png new file mode 100644 index 00000000000..4410948cf84 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-custom-install-linux.png differ diff --git a/releases/0.47/img/react-native-android-studio-custom-install-windows.png b/releases/0.47/img/react-native-android-studio-custom-install-windows.png new file mode 100644 index 00000000000..7ed385a00e7 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-custom-install-windows.png differ diff --git a/releases/0.47/img/react-native-android-studio-custom-install.png b/releases/0.47/img/react-native-android-studio-custom-install.png new file mode 100644 index 00000000000..01ab7b2ac01 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-custom-install.png differ diff --git a/releases/0.47/img/react-native-android-studio-kvm-linux.png b/releases/0.47/img/react-native-android-studio-kvm-linux.png new file mode 100644 index 00000000000..dab081084e6 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-kvm-linux.png differ diff --git a/releases/0.47/img/react-native-android-studio-no-virtual-device-windows.png b/releases/0.47/img/react-native-android-studio-no-virtual-device-windows.png new file mode 100644 index 00000000000..933a583f03d Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-no-virtual-device-windows.png differ diff --git a/releases/0.47/img/react-native-android-studio-verify-installs-windows.png b/releases/0.47/img/react-native-android-studio-verify-installs-windows.png new file mode 100644 index 00000000000..8f0cf1b2e20 Binary files /dev/null and b/releases/0.47/img/react-native-android-studio-verify-installs-windows.png differ diff --git a/releases/0.47/img/react-native-android-tools-environment-variable-windows.png b/releases/0.47/img/react-native-android-tools-environment-variable-windows.png new file mode 100644 index 00000000000..5ddeb614977 Binary files /dev/null and b/releases/0.47/img/react-native-android-tools-environment-variable-windows.png differ diff --git a/releases/0.47/img/react-native-congratulations.png b/releases/0.47/img/react-native-congratulations.png new file mode 100644 index 00000000000..92f520ec123 Binary files /dev/null and b/releases/0.47/img/react-native-congratulations.png differ diff --git a/releases/0.47/img/react-native-existing-app-integration-ios-before.png b/releases/0.47/img/react-native-existing-app-integration-ios-before.png new file mode 100644 index 00000000000..445dd790444 Binary files /dev/null and b/releases/0.47/img/react-native-existing-app-integration-ios-before.png differ diff --git a/releases/0.47/img/react-native-sdk-platforms.png b/releases/0.47/img/react-native-sdk-platforms.png new file mode 100644 index 00000000000..51d0317cfac Binary files /dev/null and b/releases/0.47/img/react-native-sdk-platforms.png differ diff --git a/releases/0.47/img/react-native-sorry-not-supported.png b/releases/0.47/img/react-native-sorry-not-supported.png new file mode 100644 index 00000000000..8848f4cdc6c Binary files /dev/null and b/releases/0.47/img/react-native-sorry-not-supported.png differ diff --git a/releases/0.47/img/react-native-tools-avd.png b/releases/0.47/img/react-native-tools-avd.png new file mode 100644 index 00000000000..20d7626ecbf Binary files /dev/null and b/releases/0.47/img/react-native-tools-avd.png differ diff --git a/releases/0.47/img/search.png b/releases/0.47/img/search.png new file mode 100644 index 00000000000..222fb660dae Binary files /dev/null and b/releases/0.47/img/search.png differ diff --git a/releases/0.47/img/showcase/wmt_spark.png b/releases/0.47/img/showcase/wmt_spark.png new file mode 100644 index 00000000000..88039cf81f3 Binary files /dev/null and b/releases/0.47/img/showcase/wmt_spark.png differ diff --git a/releases/0.47/img/survey.png b/releases/0.47/img/survey.png new file mode 100644 index 00000000000..af025067da2 Binary files /dev/null and b/releases/0.47/img/survey.png differ diff --git a/releases/0.47/img/uiexplorer_main_android.png b/releases/0.47/img/uiexplorer_main_android.png new file mode 100644 index 00000000000..d510e7aded3 Binary files /dev/null and b/releases/0.47/img/uiexplorer_main_android.png differ diff --git a/releases/0.47/img/uiexplorer_main_ios.png b/releases/0.47/img/uiexplorer_main_ios.png new file mode 100644 index 00000000000..2274ef2dfb4 Binary files /dev/null and b/releases/0.47/img/uiexplorer_main_ios.png differ diff --git a/releases/0.47/index.html b/releases/0.47/index.html new file mode 100644 index 00000000000..9181e23d7a8 --- /dev/null +++ b/releases/0.47/index.html @@ -0,0 +1,76 @@ +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 { + render() { + return ( + <View> + <Text> + If you like React on the web, you'll like React Native. + </Text> + <Text> + You just use native components like 'View' and 'Text', + instead of web components like 'div' and 'span'. + </Text> + </View> + ); + } +}

A React Native app is a real mobile app

With React Native, you don't build a “mobile web app”, an “HTML5 app”, or a “hybrid app”. You build a real mobile app that's indistinguishable from an app built using Objective-C or Java. React Native uses the same fundamental UI building blocks as regular iOS and Android apps. You just put those building blocks together using JavaScript and React.

import React, { Component } from 'react'; +import { Image, ScrollView, Text } from 'react-native'; + +class AwkwardScrollingImageWithText extends Component { + render() { + return ( + <ScrollView> + <Image + source={{uri: 'https://i.chzbgr.com/full/7345954048/h7E2C65F9/'}} + style={{width: 320, height:180}} + /> + <Text> + On iOS, a React Native ScrollView uses a native UIScrollView. + On Android, it uses a native ScrollView. + + On iOS, a React Native Image uses a native UIImageView. + On Android, it uses a native ImageView. + + React Native wraps the fundamental native components, giving you + the performance of a native app, plus the clean design of React. + </Text> + </ScrollView> + ); + } +}

Don't waste time recompiling

React Native lets you build your app faster. Instead of recompiling, you can reload your app instantly. With Hot Reloading, you can even run new code while retaining your application state. Give it a try - it's a magical experience.


Use native code when you need to

React Native combines smoothly with components written in Objective-C, Java, or Swift. It's simple to drop down to native code if you need to optimize a few aspects of your application. It's also easy to build part of your app in React Native, and part of your app using native code directly - that's how the Facebook app works.

import React, { Component } from 'react'; +import { Text, View } from 'react-native'; +import { TheGreatestComponentInTheWorld } from './your-native-code'; + +class SomethingFast extends Component { + render() { + return ( + <View> + <TheGreatestComponentInTheWorld /> + <Text> + TheGreatestComponentInTheWorld could use native Objective-C, + Java, or Swift - the product development process is the same. + </Text> + </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
F8
Airbnb
Walmart
Tesla
Tencent QQ
\ No newline at end of file diff --git a/releases/0.47/js/scripts.js b/releases/0.47/js/scripts.js new file mode 100644 index 00000000000..adf2deeaac1 --- /dev/null +++ b/releases/0.47/js/scripts.js @@ -0,0 +1,300 @@ +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +/* eslint-disable module-strict */ + +(function() { + 'use strict'; + // Not on browser + if (typeof document === 'undefined') { + return; + } + + document.addEventListener('DOMContentLoaded', init); + + function init() { + var mobile = isMobile(); + + if (mobile) { + document + .querySelector('.nav-site-wrapper a[data-target]') + .addEventListener('click', toggleTarget); + } + + var webPlayerList = document.querySelectorAll( + '.web-player' + ); + + // Either show interactive or static code block, depending on desktop or mobile + for (var i = 0; i < webPlayerList.length; ++i) { + webPlayerList[i].classList.add( + mobile ? 'mobile' : 'desktop' + ); + + if (!mobile) { + // Determine location to look up required assets + 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; + } + } + + 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(); + } + } + + // handle tabs in docs + convertBlocks(); + guessPlatformAndOS(); + + var backdrop = document.querySelector( + '.modal-backdrop' + ); + if (!backdrop) { + return; + } + + var modalButtonOpenList = document.querySelectorAll( + '.modal-button-open' + ); + var modalButtonClose = document.querySelector( + '.modal-button-close' + ); + + backdrop.addEventListener('click', hideModal); + modalButtonClose.addEventListener('click', hideModal); + + // Bind event to NodeList items + for (var i = 0; i < modalButtonOpenList.length; ++i) { + modalButtonOpenList[i].addEventListener( + 'click', + showModal + ); + } + } + + function showModal(e) { + var backdrop = document.querySelector( + '.modal-backdrop' + ); + if (!backdrop) { + return; + } + + var modal = document.querySelector('.modal'); + + backdrop.classList.add('modal-open'); + modal.classList.add('modal-open'); + } + + function hideModal(e) { + var backdrop = document.querySelector( + '.modal-backdrop' + ); + if (!backdrop) { + return; + } + + var modal = document.querySelector('.modal'); + + backdrop.classList.remove('modal-open'); + modal.classList.remove('modal-open'); + } + + var toggledTarget; + function toggleTarget(event) { + var target = document.body.querySelector( + event.target.getAttribute('data-target') + ); + + if (target) { + event.preventDefault(); + + if (toggledTarget === target) { + toggledTarget.classList.toggle('in'); + } else { + toggledTarget && + toggledTarget.classList.remove('in'); + target.classList.add('in'); + } + + toggledTarget = target; + } + } + + // Primitive mobile detection + function isMobile() { + return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( + navigator.userAgent + ); + } + + function convertBlocks() { + // Convert
......
+ // Into
......
+ var blocks = document.querySelectorAll('block'); + for (var i = 0; i < blocks.length; ++i) { + var block = blocks[i]; + var span = blocks[i].parentNode; + var container = span.parentNode; + container.insertBefore(block, span); + container.removeChild(span); + } + // Convert
...content...
+ // Into
...content...
+ blocks = document.querySelectorAll('block'); + for (var i = 0; i < blocks.length; ++i) { + var block = blocks[i]; + while ( + block.nextSibling && + block.nextSibling.tagName !== 'BLOCK' + ) { + block.appendChild(block.nextSibling); + } + } + } + + function displayTab(type, value) { + var container = document.querySelectorAll('block')[ + 0 + ].parentNode; + container.className = 'display-' + + type + + '-' + + value + + ' ' + + container.className.replace( + RegExp('display-' + type + '-[a-z]+ ?'), + '' + ); + } + + function guessPlatformAndOS() { + if (!document.querySelector('block')) { + return; + } + + // If we are coming to the page with a hash in it (i.e. from a search, for example), try to get + // us as close as possible to the correct platform and dev os using the hashtag and block walk up. + var foundHash = false; + if ( + window.location.hash !== '' && + window.location.hash !== 'content' + ) { + // content is default + var hashLinks = document.querySelectorAll( + 'a.hash-link' + ); + for ( + var i = 0; + i < hashLinks.length && !foundHash; + ++i + ) { + if (hashLinks[i].hash === window.location.hash) { + var parent = hashLinks[i].parentElement; + while (parent) { + if (parent.tagName === 'BLOCK') { + var gettingStartedGuideType = null; + var devOS = null; + var targetPlatform = null; + // Could be more than one target os and dev platform, but just choose some sort of order + // of priority here. + + // Dev OS + if (parent.className.indexOf('mac') > -1) { + displayTab('os', 'mac'); + foundHash = true; + } else if ( + parent.className.indexOf('linux') > -1 + ) { + displayTab('os', 'linux'); + foundHash = true; + } else if ( + parent.className.indexOf('windows') > -1 + ) { + displayTab('os', 'windows'); + foundHash = true; + } else { + break; + } + + // Target Platform + if (parent.className.indexOf('ios') > -1) { + displayTab('platform', 'ios'); + foundHash = true; + } else if ( + parent.className.indexOf('android') > -1 + ) { + displayTab('platform', 'android'); + foundHash = true; + } else { + break; + } + + // Guide + if (parent.className.indexOf('native') > -1) { + displayTab('guide', 'native'); + foundHash = true; + } else if ( + parent.className.indexOf('quickstart') > -1 + ) { + displayTab('guide', 'quickstart'); + foundHash = true; + } else { + break; + } + + break; + } + parent = parent.parentElement; + } + } + } + } + + // Do the default if there is no matching hash + if (!foundHash) { + var isMac = navigator.platform === 'MacIntel'; + var isWindows = navigator.platform === 'Win32'; + displayTab('platform', isMac ? 'ios' : 'android'); + displayTab( + 'os', + isMac ? 'mac' : isWindows ? 'windows' : 'linux' + ); + displayTab('guide', 'quickstart'); + displayTab('language', 'objc'); + } + } +})(); diff --git a/releases/0.47/movies.json b/releases/0.47/movies.json new file mode 100644 index 00000000000..fd48f44a9f5 --- /dev/null +++ b/releases/0.47/movies.json @@ -0,0 +1,11 @@ +{ + "title": "The Basics - Networking", + "description": "Your app fetched this from a remote endpoint!", + "movies": [ + { "title": "Star Wars", "releaseYear": "1977"}, + { "title": "Back to the Future", "releaseYear": "1985"}, + { "title": "The Matrix", "releaseYear": "1999"}, + { "title": "Inception", "releaseYear": "2010"}, + { "title": "Interstellar", "releaseYear": "2014"} + ] +} diff --git a/releases/0.47/versions.html b/releases/0.47/versions.html new file mode 100644 index 00000000000..9339c50dbed --- /dev/null +++ b/releases/0.47/versions.html @@ -0,0 +1,19 @@ +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.46DocumentationRelease Notes

This is the version that is configured automatically when you create a new project using react-native init.

Pre-release versions

masterDocumentation
0.47-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.45DocumentationRelease Notes
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 diff --git a/versions.html b/versions.html index f82105c581d..9339c50dbed 100644 --- a/versions.html +++ b/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.46DocumentationRelease 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.45DocumentationRelease Notes
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.46DocumentationRelease Notes

This is the version that is configured automatically when you create a new project using react-native init.

Pre-release versions

masterDocumentation
0.47-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.45DocumentationRelease Notes
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 + \ No newline at end of file