diff --git a/releases/0.37/404.html b/releases/0.37/404.html new file mode 100644 index 00000000000..db93f09777f --- /dev/null +++ b/releases/0.37/404.html @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/releases/0.37/circle.yml b/releases/0.37/circle.yml new file mode 100644 index 00000000000..56ad41b2f14 --- /dev/null +++ b/releases/0.37/circle.yml @@ -0,0 +1,4 @@ +general: + branches: + ignore: + - gh-pages diff --git a/releases/0.37/css/react-native.css b/releases/0.37/css/react-native.css new file mode 100644 index 00000000000..4fdc9138d24 --- /dev/null +++ b/releases/0.37/css/react-native.css @@ -0,0 +1,1966 @@ +html { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-family: proxima-nova, "Helvetica Neue", Helvetica, Arial, sans-serif; + color: #484848; + line-height: 1.28; +} + +body { + background-color: #F5FCFF; +} + +p { + margin: 0 0 10px; +} + +.subHeader { + font-size: 21px; + font-weight: 300; + line-height: 30px; + margin-bottom: 10px; +} + +em { + font-style: italic; +} + +h1, h2, h3, h4, h5, h6 { + margin: 10px 0; + font-family: inherit; + font-weight: bold; + line-height: 20px; + color: inherit; + 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: 39px; +} + +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: #0485A9; + 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; +} + +.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; + } +} + +.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; +} + +.side-by-side { + overflow: hidden; +} + +.side-by-side > div { + width: 460; + margin-left: 0; + float: left; +} + +* { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + border: none; + margin: 0; + padding: 0; +} + +.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: #3B3738; + color: #fafafa; + position: fixed; + top: 0; + min-height: 50px; + box-shadow: 0 0 5px rgba(0, 0, 0, 0.5); + width: 100%; + z-index: 100; +} + +.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; +} + +.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; + color: #ddd; +} + +.nav-main .nav-site a:hover { + color: #fff; +} + +.nav-main .nav-site a.active { + color: #fff; + border-bottom: 3px solid #05A5D1; + background: #333; +} + +.nav-main .nav-home { + font-size: 24px; + 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: 800; + color: #05A5D1; + 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: bold; + 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; + } +} + +.hero { + background: #2D2D2D; + padding: 50px 0; + color: #FDF3E7; + font-weight: 300; +} + +.hero .text { + font-size: 64px; + text-align: center; +} + +.hero .minitext { + font-size: 16px; + text-align: center; + text-transform: uppercase; +} + +.hero strong { + font-weight: 400; +} + +.buttons-unit { + margin-top: 40px; + text-align: center; +} + +.buttons-unit a { + color: #FA6900; +} + +.buttons-unit .button { + font-size: 24px; + background: #05A5D1; + color: #fafafa; +} + +.buttons-unit .button:active { + background: #0485A9; +} + +.buttons-unit.downloads { + margin: 30px 0; +} + +.nav-docs { + font-size: 14px; + float: left; + width: 210px; + margin: 5px 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 h3 { + text-transform: uppercase; + font-size: 14px; +} + +.nav-docs a { + color: #666; + display: block; +} + +.nav-docs a:hover { + text-decoration: none; + color: #0485A9; +} + +.nav-docs a.active { + color: #0485A9; +} + +.nav-docs h3 { + line-height: 25px; + margin-top: 12px; + margin-bottom: 5px; +} + +.nav-docs .nav-docs-section:first-child h3 { + margin-top: 0; +} + +.nav-docs .nav-docs-section:first-child { + padding-top: 0; + border-top: 0; +} + +.nav-docs .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 rgb(5, 165, 209); + padding: 25px; + overflow: scroll; + -webkit-overflow-scrolling: touch; + position: relative; + width: 100%; + height: 100%; + } + + /* Active state */ + .nav-docs.in { + top: 0; + -webkit-animation: slide-in 0.3s forwards; + -moz-animation: slide-in 0.3s forwards; + -o-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: rgb(5, 165, 209); + } +} + +/** + * 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 + /*Phone, landscape screen orientation*/ + only screen and (min-device-width : 375px) and (max-device-width : 1024px) and (orientation : landscape), + /*Tablet, portrait screen orientation*/ + 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%; + } +} + +.nav-blog li { + margin-bottom: 5px; +} + +.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: 14px proxima-nova, "Helvetica Neue", Helvetica, Arial, sans-serif; + padding: 3px; + width: 150px; +} + +#examples #todoExample button { + font: 14px proxima-nova, "Helvetica Neue", Helvetica, Arial, sans-serif; + margin-left: 5px; + padding: 4px 10px; +} + +#examples #markdownExample textarea { + border: 1px solid #ccc; + font: 14px proxima-nova, "Helvetica Neue", Helvetica, Arial, sans-serif; + margin-bottom: 10px; + padding: 5px; +} + +.home-bottom-section { + margin-bottom: 100px; +} + +.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 { + padding-top: 20px; + 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: 400; + 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); + text-decoration: none; +} + +.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: 10px 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,.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,.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: hsl(198, 100%, 96%); +} + +.compactProps { + border-left: 2px solid hsl(198, 100%, 94%); + margin-left: 20px; + padding-left: 5px; +} + +.props > .prop:nth-child(2n) { + background-color: hsl(198, 100%, 94%); +} + +.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: #2F9C0A; +} + +.compactProps .methodTitle { + font-size: 14px; + margin-bottom: 0; + margin-top: 0; +} + +.compactProps .methodTitle div { + font-weight: normal; + margin-left: 20px; +} + +.prop { + padding: 5px 10px; +} + +.compactProps .prop { + padding: 3px 10px; +} + +.propType { + font-weight: normal; + font-size: 15px; + white-space: pre; +} + +.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: hsl(198, 100%, 87%); + border-radius: 5px; + margin-right: 5px; + padding: 0 5px; + font-size: 13px; + font-weight: normal; + -webkit-user-select: none; + -moz-user-select: none; + -ms-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; +} + + +/** Showcase **/ + +.home-showcase-section { + max-width: 800px; + margin: 20px auto 40px 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: 110px; + border-radius: 20px; +} + +.showcaseHeader { + padding-bottom: 15px; + padding-top: 15px; + text-align: center; +} + +.showcase { + margin: 30px auto 30px auto; + width: 100%; + display: inline-block; + text-align: center; + vertical-align: top; +} + +@media only screen + and (min-device-width: 768px) + and (max-device-width: 1024px) { + .showcase { + width: 50%; + } +} + +@media only screen + and (min-device-width: 1024px) { + .showcase { + width: 25%; + } +} + +.showcase h3 { + margin-bottom: 0px; + line-height: 20px; + padding-left: 5px; + padding-right: 5px; + font-size: 16px; +} + +.showcase p { + margin-top: 5px; + font-weight: normal; +} + +.showcase a { + font-weight: bold; +} + +.showcase h3, .showcase p { + color: rgb(72, 72, 72); +} + +.showcase img { + width: 100px; + border-radius: 20px; +} + +.pinned img { + width: 150px; + border-radius: 20px; +} + +table.versions { + width: 60%; +} + +.versions th { + width: 20%; +} + +.versions td, .versions th { + padding: 2px 5px; +} + +.versions tr:nth-child(2n+1) { + background-color: hsl(198, 100%, 94%); +} + +@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%; + } +} + +/** Algolia Doc Search **/ + + +div.algolia-search-wrapper { + display: inline-block; + vertical-align: top; + margin-left: 15px; +} + +.algolia-autocomplete .aa-dropdown-menu { + margin-left: -210px; + margin-top: -4px; +} + +@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; + + padding: 0 10px; + padding-left: 35px; + margin-top: 10px; + height: 30px; + font-size: 16px; + line-height: 20px; + background-color: #555; + border-radius: 4px; + color: white; + outline: none; + border: none; + width: 170px; + transition: .5s width ease; + -webkit-transition: .5s width ease; + -moz-transition: .5s width ease; + -o-transition: .5s width ease; +} + +input#algolia-doc-search:focus { + width: 220px; +} + +.algolia-autocomplete { + vertical-align: top; + height: 53px; +} + +.algolia-docsearch-suggestion--category-header { + background-color: #3B3738; +} +.algolia-docsearch-suggestion--highlight { + color: #05A5D1; +} +.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: hsl(198, 100%, 96%); +} +.algolia-docsearch-suggestion { + border-bottom-color: hsl(198, 100%, 94%); +} +.algolia-docsearch-suggestion--subcategory-column { + border-right-color: hsl(198, 100%, 94%); + background-color: hsl(198, 100%, 96%); + color: #3B3738; +} + +.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: hsl(198, 75%, 88%); + 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-bottom: 40px; + font-size: 12px; + color: #887766; + text-align: center; + background-color: rgba(5, 165, 209, 0.05); +} + +/** Web player **/ + +.web-player > iframe, .web-player > .prism { + display: none; +} + +.web-player.desktop > iframe { + display: block; +} + +.web-player.mobile > .prism { + display: block; +} + +/** Blog **/ + +.entry-header { + margin: 40px 0 0 0; +} + +.entry-header h1 { + margin: 0; + font-size: 33px; + line-height: 36px; +} + +.entry-header h4 { + margin: 0 0 10px; + font-size: 12px; + line-height: 16px; +} + +.entry-header .author { + color: #5A6b77; +} + +.entry-header .date { + color: #66637A; +} + +.entry-readmore { + margin: 12px 0 0; +} + +.entry-share { + padding: 36px 0; + display: block; + text-align: left; +} + +.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; + line-height: 1.7; +} + +article h2 { + font-size: 26px; + line-height: 30px; +} + +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: rgba(102,99,122,.29); + 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: rgba(102,99,122,.44); +} + +.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; + font-size: 12px; +} + +.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; + } +} + +/** 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; +} + +/** Footer **/ + +footer.nav-footer { + box-sizing: border-box; + border: none; + font-weight: 300; + color: #202020; + font-size: 15px; + line-height: 24px; + background: #2D2D2D; + box-shadow: inset 0 10px 10px -5px #0d1116; + 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 3em; +} +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: 740px) { + footer .sitemap { + 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; +} +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; +} diff --git a/releases/0.37/docs/accessibility.html b/releases/0.37/docs/accessibility.html new file mode 100644 index 00000000000..03aa0fc42a4 --- /dev/null +++ b/releases/0.37/docs/accessibility.html @@ -0,0 +1,59 @@ +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.
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}’.
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.
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:
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.
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:
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.
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.
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.
In the above example, the TouchableWithoutFeedback is being announced by TalkBack as a native Button.
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’:
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.
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).
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.
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.
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.
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 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!
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 optionsdestructiveButtonIndex (int) - index of destructive button in optionstitle (string) - a title to show above the action sheetmessage (string) - a message to show below the titleDisplay 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 sharemessage (string) - a message to sharesubject (string) - a subject for the messageexcludedActivityTypes (array) - the activities to exclude from the ActionSheetNOTE: if url points to a local file, or is a base64-encoded
+uri, the file it points to will be loaded and shared directly.
+In this way, you can share images, videos, PDF files, etc.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
Displays a circular loading indicator.
Whether to show the indicator (true, the default) or hide it (false).
Size of the indicator (default is 'small'). +Passing a number to the size prop is only supported on Android.
Whether the indicator should hide when not animating (true by default).
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
On iOS you can specify any number of buttons. Each button can optionally +specify a style, which is one of 'default', 'cancel' or 'destructive'.
On Android at most three buttons can be specified. Android has a concept +of a neutral, negative and a positive button:
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
AlertIOS provides functionality to create an iOS alert dialog with a
+message or create a prompt for user input.
Creating an iOS alert:
Creating an iOS prompt:
We recommend using the Alert.alert method for
+cross-platform support if you don't need to create iOS-only prompts.
Create and display a popup alert.
| Name and Type | Description |
|---|---|
| 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 |
| [type] | Deprecated, do not use. |
Create and display a prompt to enter some text.
| Name and Type | Description |
|---|---|
| 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 |
| [type] | This configures the text input. One of 'plain-text', + 'secure-text' or 'login-password'. |
| [defaultValue] string | The default text in text input. |
An Alert button type
| Value | Description |
|---|---|
| default | Default alert with no inputs |
| plain-text | Plain text input alert |
| secure-text | Secure text input alert |
| login-password | Login and password alert |
An Alert button style
| Value | Description |
|---|---|
| default | Default button style |
| cancel | Cancel button style |
| destructive | Destructive button style |
Array or buttons
| Name and Type | Description |
|---|---|
| [text] string | Button label |
| [onPress] function | Callback function when button pressed |
| [style] | Button style |
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
Assuming you have the Android SDK installed, run android to open the Android SDK Manager.
Make sure you have the following installed:
build.gradle)build.gradle)Android Support Repository) >= 17 (for Android Support Library)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_profile or .bashrc.zprofile or .zshrc.profile or $ENVExample:
Step 2: Create a local.properties file in the android directory of your react-native app with the following contents:
Example:
You can find further instructions on the official page.
First, you need to install react-native from your fork. For example, to install the master branch from the official repo, run the following:
Alternatively, you can clone the repo to your node_modules directory and run npm install inside the cloned repo.
Add gradle-download-task as dependency in android/build.gradle:
:ReactAndroid project #Add the :ReactAndroid project in android/settings.gradle:
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'):
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 replace compile project(':react-native-custom-module') with:
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.
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:
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 Testing.
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!
We try our best to deliver buttery-smooth UI performance by default, but sometimes that just isn't possible. Remember, 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. But first...
Make sure that JS dev mode is OFF!
You should see
__DEV__ === false, development-level warning are OFF, performance optimizations are ONin your application logs (which you can view usingadb logcat)
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 markers 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.
NOTE:
Systrace support was added in react-native
v0.15. You will need to build with that version to collect 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
A quick breakdown of this command:
time is the length of time the trace will be collected in secondssched, 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.appOnce 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.
After opening the trace in your browser (preferably Chrome), you should see something like this:

If your trace .html file isn't opening correctly, check your browser console for the following:

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:
HINT: Use the WASD keys to strafe and zoom
The first thing you should do is highlight the 16ms frame boundaries if you haven't already done that. Check this checkbox at the top right of the screen:

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.
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 three/four 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.
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:

This is where JS 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:

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:

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:

A smooth animation should look something like the following:

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 60FPS.
If you noticed chop, however, you might see something like this:

Notice that the JS thread is executing basically all the time, and across frame boundaries! This app is not rendering at 60FPS. In this case, the problem lies in JS.
You might also see something like this:

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

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.
TODO: Add more tools for profiling JS
If you identified a native UI problem, there are usually two scenarios:
In the first scenario, you'll see a trace that has the UI thread and/or Render Thread looking like this:

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:
renderToHardwareTextureAndroid for complex, static content that is being animated/transformed (e.g. the Navigator slide/alpha animations)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.
In the second scenario, you'll see something more like this:

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.
If you are confused or stuck, please post ask on Stack Overflow with the react-native tag. If you are unable to get a response there, or find an issue with a core component, please File a Github issue.
You can edit the content above on GitHub and send us a pull request!
Animations are an important part of modern UX, and the Animated
+library is designed to make them fluid, powerful, and easy to build and
+maintain.
The simplest workflow is to create an Animated.Value, hook it up to one or
+more style attributes of an animated component, and then drive updates either
+via animations, such as Animated.timing, or by hooking into gestures like
+panning or scrolling via Animated.event. Animated.Value can also bind to
+props other than style, and can be interpolated as well. Here is a basic
+example of a container view that will fade in when it's mounted:
Note that only animatable components can be animated. View, Text, and
+Image are already provided, and you can create custom ones with
+createAnimatedComponent. 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.
Animations are heavily configurable. Custom and pre-defined easing +functions, delays, durations, decay factors, spring constants, and more can +all be tweaked depending on the type of animation.
A single Animated.Value can drive any number of properties, and 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.
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 in the example above like so:
Animations can also be combined in complex ways using composition functions
+such as sequence and parallel, and can also be chained together simply
+by setting the toValue of one animation to be another Animated.Value.
Animated.ValueXY is handy for 2D animations, like panning, and there are
+other helpful additions like setOffset and getLayout to aid with typical
+interaction patterns, like drag-and-drop.
You can see more example usage in AnimationExample.js, the Gratuitous
+Animation App, and Animations documentation guide.
Note that 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.
+Checkout 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.
Animates a value from an initial velocity to zero based on a decay +coefficient.
Animates a value along a timed easing curve. The Easing module has tons
+of pre-defined curves, or you can use your own function.
Spring animation based on Rebound and Origami. Tracks velocity state to
+create fluid motions as the toValue updates, and can be chained together.
Creates a new Animated value composed from two Animated values added +together.
Creates a new Animated value composed by dividing the first Animated value +by the second Animated value.
Creates a new Animated value composed from two Animated values multiplied +together.
Creates a new Animated value that is the (non-negative) modulo of the +provided Animated value
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.
Starts an animation after the given delay.
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.
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.
Array of animations may run in parallel (overlap), but are started in +sequence with successive delays. Nice for doing trailing effects.
Takes an array of mappings and extracts values from each arg accordingly,
+ then calls setValue on the mapped outputs. e.g.
Make any React component Animatable. Used to create Animated.View, etc.
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.
Directly set the value. This will stop any animations running on the value +and update all the bound properties.
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.
Merges the offset value into the base value and resets the offset to zero. +The final output of the value is unchanged.
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.
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.
Interpolates the value before updating the property, e.g. mapping 0-1 to +0-10.
Typically only used internally, but could be used by a custom Animation +class.
Typically only used internally.
Typically only used internally.
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:
Converts {x, y} into {left, top} for use in style, e.g.
Converts {x, y} into a useable translation transform, e.g.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
Fluid, meaningful animations are essential to the mobile user experience. Like
+everything in React Native, Animation APIs for React Native are currently under
+development, but have started to coalesce around two complementary systems:
+LayoutAnimation for animated global layout transactions, and Animated for
+more granular and interactive control of specific values.
The Animated library 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. For example, a complete
+component with a simple spring bounce on mount looks like this:
bounceValue is initialized as part of state in the constructor, and mapped
+to the scale transform on the image. Behind the scenes, the numeric value is
+extracted and used to set scale. When the component mounts, the scale is set to
+1.5 and then a spring animation is started on bounceValue which will update
+all of its dependent mappings on each frame as the spring animates (in this
+case, just the scale). 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.
Most everything you need hangs directly off the Animated module. This
+includes two value types, Value for single values and ValueXY for vectors,
+three animation types, spring, decay, and timing, and three component
+types, View, Text, and Image. You can make any other component animated with
+Animated.createAnimatedComponent.
The three animation types can be used to create almost any animation curve you +want because each can be customized:
spring: Simple single-spring physics model that matches Origami.friction: Controls "bounciness"/overshoot. Default 7.tension: Controls speed. Default 40.decay: Starts with an initial velocity and gradually slows to a stop.velocity: Initial velocity. Required.deceleration: Rate of decay. Default 0.997.timing: Maps time range to easing value.duration: Length of animation (milliseconds). Default 500.easing: Easing function to define curve. See Easing module for several
+predefined functions. iOS default is Easing.inOut(Easing.ease).delay: Start the animation after delay (milliseconds). Default 0.Animations are started by calling start. start takes a completion callback
+that will be called when the animation is done. If the animation is done
+because it finished running normally, the completion callback will be invoked
+with {finished: true}, but 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}.
Animations can also be composed with parallel, sequence, stagger, and
+delay, each of which simply take an array of animations to execute and
+automatically calls start/stop as appropriate. For example:
By default, if one animation is stopped or interrupted, then all other
+animations in the group are also stopped. Parallel has a stopTogether option
+that can be set to false to disable this.
Another powerful part of the Animated API is the interpolate function. It
+allows input ranges to map to different output ranges. For example, a simple
+mapping to convert a 0-1 range to a 0-100 range would be
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:
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:
interpolation also supports arbitrary easing functions, many of which are
+already implemented in the
+Easing
+class including quadratic, exponential, and bezier curves as well as functions
+like step and bounce. interpolation 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.
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 with
+spring physics for an interaction like "Chat Heads", or via timing with
+duration: 0 for rigid/instant tracking. They can also be composed with
+interpolations:
ValueXY is a handy way to deal with 2D interactions, such as panning/dragging.
+It is a simple wrapper that basically just 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. For example, in the code
+snippet above, leader and follower could both be of type ValueXY and the x
+and y values will both track as you would expect.
Animated.event is the input side of the Animated API, allowing gestures and
+other events to map directly to animated values. 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. In the example, you can see that scrollX maps to
+event.nativeEvent.contentOffset.x (event is normally the first arg to the
+handler), and pan.x and pan.y map to gestureState.dx and gestureState.dy,
+respectively (gestureState is the second arg passed to the PanResponder handler).
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 60fps.As previously mentioned, we're planning on optimizing Animated under the hood to +make it even more performant. We would also like to experiment with more +declarative and higher level gestures and triggers, such as horizontal vs. +vertical panning.
The above API gives a powerful tool for expressing all sorts of animations in a
+concise, robust, and performant way. Check out more example code in
+UIExplorer/AnimationExample. Of course there may still be times where Animated
+doesn't support what you need, and the following sections cover other animation
+systems.
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:

This example uses a preset value, you can customize the animations as +you need, see LayoutAnimation.js +for more information.
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.
react-tween-state is a
+minimal library that does exactly what its name suggests: it tweens a
+value in a component's state, starting at a from value and ending at
+a to value. This means that it generates the values in between those
+two values, and it sets the state on every requestAnimationFrame with
+the intermediary value.
Tweening definition from Wikipedia
"... tweening is the process of generating intermediate frames between two +images to give the appearance that the first image evolves smoothly +into the second image. [Tweens] are the drawings between the key +frames which help to create the illusion of motion."
The most obvious way to animate from one value to another is linearly: +you subtract the end value from the start value and divide the result by +the number of frames over which the animation occurs, and then add that +value to the current value on each frame until the end value is reached. +Linear easing often looks awkward and unnatural, so react-tween-state +provides a selection of popular easing functions +that can be applied to make your animations more pleasing.
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-tween-state
+--save from your project directory.

Here we animated the opacity, but as you might guess, we can animate any +numeric value. Read more about react-tween-state in its +README.
Rebound.js is a JavaScript port of
+Rebound for Android. It is
+similar in concept to react-tween-state: you have an initial value and
+set an end value, then Rebound generates intermediate values that you can
+use for your animation. Rebound is modeled after spring physics; we
+don't provide a duration when animating with springs, it is
+calculated for us depending on the spring tension, friction, current
+value and end value. Rebound is used
+internally
+by React Native on Navigator and WarningBox.

Notice that Rebound animations can be interrupted - if you release in +the middle of a press, it will animate back from the current state to +the original value.
You can also clamp the spring values so that they don't overshoot and
+oscillate around the end value. In the above example, we would add
+this._scrollSpring.setOvershootClampingEnabled(true) to change this.
+See the below gif for an example of where in your interface you might
+use this.
Screenshot from
+react-native-scrollable-tab-view.
+You can run a similar example here.
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.
It would not make sense to use setNativeProps with react-tween-state
+because the updated tween values are set on the state automatically by
+the library - Rebound on the other hand gives us an updated value for
+each frame with the onSpringUpdate function.
If you find your animations with dropping frames (performing below 60
+frames per second), look into using setNativeProps or
+shouldComponentUpdate to optimize them. You may also want to defer any
+computationally intensive work until after animations are complete,
+using the
+InteractionManager. You
+can monitor the frame rate by using the In-App Developer Menu "FPS
+Monitor" tool.
As mentioned in the Navigator
+Comparison,
+Navigator is implemented in JavaScript and NavigatorIOS is a wrapper
+around native functionality provided by UINavigationController, so
+these scene transitions apply only to Navigator. In order to re-create
+the various animations provided by UINavigationController and also
+make them customizable, React Native exposes a
+NavigatorSceneConfigs API which is then handed over to the Navigator configureScene prop.
For further information about customizing scene transitions, read the +source.
You can edit the content above on GitHub and send us a pull request!
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
+pass 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.
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.
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!
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.
active - The app is running in the foregroundbackground - The app is running in the background. The user is either
+ in another app or on the home screeninactive - 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 callFor more information, see +Apple's documentation
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.
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.
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).
Remove a handler by passing the change event type and the handler
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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:
Fetching data:
Fetches an item for a key and invokes a callback upon completion.
+Returns a Promise object.
| Name and Type | Description |
|---|---|
| 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. |
Sets the value for a key and invokes a callback upon completion.
+Returns a Promise object.
| Name and Type | Description |
|---|---|
| key string | Key of the item to set. |
| value string | Value to set for the |
| [callback] ?(error: ?Error) => void | Function that will be called with any error. |
Removes an item for a key and invokes a callback upon completion.
+Returns a Promise object.
| Name and Type | Description |
|---|---|
| key string | Key of the item to remove. |
| [callback] ?(error: ?Error) => void | Function that will be called with any error. |
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.
| Name and Type | Description |
|---|---|
| key string | Key of the item to modify. |
| value string | New value to merge for the |
| [callback] ?(error: ?Error) => void | Function that will be called with any error. |
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.
| Name and Type | Description |
|---|---|
| [callback] ?(error: ?Error) => void | Function that will be called with any error. |
Gets all keys known to your app; for all callers, libraries, etc.
+Returns a Promise object.
| Name and Type | Description |
|---|---|
| [callback] ?(error: ?Error, keys: ?Array<string>) => void | Function that will be called the keys found and any error. |
Flushes any pending requests using a single batch call to get the data.
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:
The method returns a Promise object.
| Name and Type | Description |
|---|---|
| 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. |
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:
The method returns a Promise object.
| Name and Type | Description |
|---|---|
| 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. |
Call this to batch the deletion of all keys in the keys array. Returns
+a Promise object.
| Name and Type | Description |
|---|---|
| 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. |
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.
| Name and Type | Description |
|---|---|
| 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. |
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
Example:
You can edit the content above on GitHub and send us a pull request!
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:
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
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.
Returns a Promise with photo identifier objects from the local camera
+roll of the device matching shape defined by getPhotosReturnChecker.
@param {object} params See getPhotosParamChecker.
Returns a Promise which when resolved will be of shape getPhotosReturnChecker.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
Clipboard gives you an interface for setting and getting content from Clipboard on both iOS and Android
Get content of string type, this method returns a Promise, so you can use following code to get clipboard content
Set content of string type. You can use following code to set clipboard content
@param the content to be stored in the clipboard.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
The following formats are supported:
'#f0f' (#rgb)'#f0fc' (#rgba)'#ff00ff' (#rrggbb)'#ff00ff00' (#rrggbbaa)'rgb(255, 255, 255)''rgba(255, 255, 255, 1.0)''hsl(360, 100%, 100%)''hsla(360, 100%, 100%, 1.0)''transparent''red'0xff00ff00 (0xrrggbbaa)For the named colors, React Native follows the CSS3 specification:
You can edit the content above on GitHub and send us a pull request!
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.
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 own internal state. We do this with properties: data is passed from a parent to its children in a top-down manner. If we have an ancestor component that rely on the state of its descendant, the recommended solution would be to pass down a callback that would 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 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.
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.
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.
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
componentWillReceivePropsandcomponentWillUpdatePropsof the top level RN component will not be called after a prop update. However, you can access the new props incomponentWillMountfunction.
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.
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.
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.
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:
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.
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 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. 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.
When integrating native and React Native, we also need a way to consolidate two different layout systems. This section covers common layouting problems and provides a brief description of mechanisms that are intended to address them.
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.
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:
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.
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.
ScrollView component. This guarantees that your content will always be available and it won't overlap with native views.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:
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 usingRCTRootViewSizeFlexibilityWidthon the hostingRCTRootView.
Let's look at an example.
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'shiddenproperty). Then change its visibility in the delegate method.
You can edit the content above on GitHub and send us a pull request!
Opens the standard Android date picker dialog.
Opens the standard Android date picker dialog.
The available keys for the options object are:
+ date (Date object or timestamp in milliseconds) - date to show by default
+ minDate (Date or timestamp in milliseconds) - minimum date that can be selected
+ * maxDate (Date object or timestamp in milliseconds) - minimum date that can be selected
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.
A date has been selected.
The dialog has been dismissed.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
The currently selected date.
Maximum date.
Restricts the range of possible date/time values.
Minimum date.
Restricts the range of possible date/time values.
The interval at which minutes can be selected.
The date picker mode.
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.
Timezone offset in minutes.
By default, the date picker will use the device's timezone. With this +parameter, it is possible to force a certain timezone offset. For +instance, to show times in Pacific Standard Time, pass -7 * 60.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
You can access the developer menu by shaking your device or by selecting "Shake Gesture" inside the Hardware menu in the iOS Simulator. You can also use the Command⌘ + D keyboard shortcut when your app is running in the iPhone Simulator, or Command⌘ + M when running in an Android emulator.

The Developer Menu is disabled in release (production) builds.
Instead of recompiling your app every time you make a change, you can reload your app's JavaScript code instantly. To do so, select "Reload" from the Developer Menu. You can also press Command⌘ + R in the iOS Simulator, or press R twice on Android emulators.
If the
Command⌘+Rkeyboard shortcut does not seem to reload the iOS Simulator, go to the Hardware menu, select Keyboard, and make sure that "Connect Hardware Keyboard" is checked.
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:
Images.xcassets on iOS or the res/drawable folder on Android.Errors and warnings are displayed inside your app in development builds.
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 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: ...'];
RedBoxes and YellowBoxes are automatically disabled in release (production) builds.
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:
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.
To debug the JavaScript code in Chrome, select "Debug JS Remotely" from the Developer Menu. This will open a new tab at http://localhost:8081/debugger-ui.
Select Tools → Developer Tools from the Chrome Menu to open the Developer Tools. You may also access the DevTools using keyboard shortcuts (Command⌘ + Option⌥ + I on Mac, Ctrl + Shift + I on Windows). You may also want to enable Pause On Caught Exceptions for a better debugging experience.
It is currently not possible to use the "React" tab in the Chrome Developer Tools to inspect app widgets. You can use Nuclide's "React Native Inspector" as a workaround.
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.
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.
In android/app/build.gradle, add these lines in the dependencies section:
In android/app/src/main/java/com/{yourAppName}/MainApplication.java, add the following imports:
In android/app/src/main/java/com/{yourAppName}/MainApplication.java add the function:
Run react-native run-android
In a new chrome tab, open : chrome://inspect, click on 'Inspect device' (the one followed by "Powered by Stetho")
When working with native code (e.g. when writing native modules) you can launch the app from Android Studio or Xcode and take advantage of the debugging features (setup breakpoints, etc.) as you would in case of building a standard native app.
You can enable a performance overlay to help you debug performance problems by selecting "Perf Monitor" in the Developer Menu.
You can edit the content above on GitHub and send us a pull request!
This should only be called from native code by sending the +didUpdateDimensions event.
@param {object} dims Simple string-keyed object of dimensions to set
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.
You can edit the content above on GitHub and send us a pull request!
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.
setNativePropsis 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 withsetState+and shouldComponentUpdate.
TouchableOpacity
+uses setNativeProps internally to update the opacity of its child
+component:
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:
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:
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 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.
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.
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:
If you update a property that is also managed by the render function,
+you might end up with some unpredictable and confusing bugs because
+anytime the component re-renders and that property changes, whatever
+value was previously set from setNativeProps will be completely
+ignored and overridden. See this example
+for a demonstration of what can happen if these two collide - notice
+the jerky animation each 250ms when setState triggers a re-render.
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.
You can edit the content above on GitHub and send us a pull request!
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:
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:
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).
Specifies the side of the screen from which the drawer will slide in.
Specifies the width of the drawer, more precisely the width of the view that be pulled in +from the edge of the window.
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.
Function called whenever the navigation view has been closed.
Function called whenever the navigation view has been opened.
Function called whenever there is an interaction with the navigation view.
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
The navigation view that will be rendered to the side of the screen and can be pulled in.
You can edit the content above on GitHub and send us a pull request!
This class implements common easing functions. The math is pretty obscure, +but this cool website has nice visual illustrations of what they represent: +http://xaedes.de/dev/transitions/
A simple elastic interaction, similar to a spring. 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.
Wolfram Plots:
http://tiny.cc/elastic_b_1 (default bounciness = 1) + http://tiny.cc/elastic_b_3 (bounciness = 3)
Runs an easing function backwards.
Makes any easing function symmetrical.
You can edit the content above on GitHub and send us a pull request!
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
flexDirectiondefaulting tocolumninstead ofrow, andalignItemsdefaulting tostretchinstead offlex-start, and theflexparameter only supports a single number.
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.
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.
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
stretchto have an effect, children must not have a fixed dimension along the secondary axis. In the following example, settingalignItems: stretchdoes nothing until thewidth: 50is removed from the children.
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!
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.
You need to include the NSLocationWhenInUseUsageDescription key
+in Info.plist to enable geolocation. Geolocation is enabled by default
+when you create a project with react-native init.
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.
Invokes the success callback once with the latest location info. Supported +options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool) +On Android, this can return almost immediately if the location is cached or +request an update, which might take a while.
Invokes the success callback whenever the location changes. Supported +options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool), distanceFilter(m)
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
Gesture recognition on mobile devices is much more complicated than web. 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.
Users can feel huge differences in the usability of web apps vs. native, and this is one of the big causes. Every action should have the following attributes:
These features make users more comfortable while using an app, because it allows people to experiment and interact without fear of making mistakes.
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.
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 happeningView.props.onResponderReject: (evt) => {} - Something else is the responder right now and will not release itIf the view is responding, the following handlers can be called:
View.props.onResponderMove: (evt) => {} - The user is moving their fingerView.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 releaseView.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:
nativeEventchangedTouches - Array of all touch events that have changed since the last eventidentifier - The ID of the touchlocationX - The X position of the touch, relative to the elementlocationY - The Y position of the touch, relative to the elementpageX - The X position of the touch, relative to the root elementpageY - The Y position of the touch, relative to the root elementtarget - The node id of the element receiving the touch eventtimeStamp - A time identifier for the touch, useful for velocity calculationtouches - Array of all current touches on the screenonStartShouldSetResponder 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,For higher-level gesture interpretation, check out PanResponder.
You can edit the content above on GitHub and send us a pull request!
Welcome to React Native! This page will help you install React Native on +your system, so that you can build apps with it right away. If you already +have React Native installed, you can skip ahead to the +Tutorial.
The instructions are a bit different depending on your development operating system, and whether you want to start developing for iOS or Android. If you +want to develop for both iOS and Android, that's fine - you just have to pick +one to start with, since the setup is a bit different.
+ + + +
You will need Node.js, Watchman, the React Native command line interface, and Xcode.
You will need Node.js, Watchman, the React Native command line interface, and Android Studio.
We recommend installing Node and Watchman using Homebrew. Run the following commands in a Terminal after installing Homebrew:
Watchman is a tool by Facebook for watching +changes in the filesystem. It is highly recommended you install it for better performance.
Node.js comes with npm, which lets you install the React Native command line interface. Run the following command in a Terminal:
If you get a permission error, try using sudo:
sudo npm install -g react-native-cli.If you get an error like
Cannot find module 'npmlog', try installing npm directly:curl -0 -L http://npmjs.org/install.sh | sudo sh.
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.
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.
Download and install Android Studio.
Android Studio installs Android 7.0 (Nougat) by default. You can confirm that the SDK was installed by clicking on "Configure" in the last screen in the Android Studio Setup Wizard, or by opening "Preferences" from the Android Studio menu, then choosing Appearance and Behavior → System Settings → Android SDK.

Select "SDK Platforms" from within the SDK Manager and you should see a blue checkmark next to "Android 7.0 (Nougat)". In case it is not, click on the checkbox and then "Apply".

If you wish to support older versions of Android, you can install additional Android SDKs from this screen.
The React Native command line interface requires the ANDROID_HOME environment variable to be set up. You can configure it in a Terminal using the following command:
To avoid doing this every time you open a new Terminal, create (or edit) ~/.bashrc using your favorite text editor and add the following lines:
The second line will add the android tool to your path, which will come in handy in the next step.
Please make sure you export the correct path for
ANDROID_HOMEif you did not install the Android SDK using Android Studio. If you install the Android SDK using Homebrew, it will be located at/usr/local/opt/android-sdk.
Android Studio should have set up an Android Virtual Device for you during installation, but it is very common to run into an issue where Android Studio fails to install the AVD.

To see the list of available AVDs, launch the "AVD Manager" from within Android Studio or run the following command in a Terminal:
You may follow the Android Studio User Guide to create a new AVD if needed.
+ +If you see "No system images installed for this target." under CPU/ABI, go back to your "SDK Manager" and click on "Show Package Details" under "SDK Platforms". You will then be able to install any missing system images, such as "Google APIs Intel Atom (x86)".
You will need Node.js, the React Native command line interface, and Android Studio.
Follow the installation instructions for your Linux distribution to install Node.js 4 or newer.
You will need Node.js, the React Native command line interface, and Android Studio.
We recommend installing Node.js and Python2 via Chocolatey, a popular package manager for Windows. Open a Command Prompt as Administrator, then run:
You can find additional installation options on Node.js's Downloads page.
Node comes with npm, which lets you install the React Native command line interface.
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.
Download and install Android Studio.
Android Studio installs Android 7.0 (Nougat) by default. You can confirm that the SDK was installed by clicking on "Configure" in the last screen in the Android Studio Setup Wizard, or by opening "Preferences" from the Android Studio menu, then choosing Appearance and Behavior → System Settings → Android SDK.

Select "SDK Platforms" from within the SDK Manager and you should see a blue checkmark next to "Android 7.0 (Nougat)". In case it is not, click on the checkbox and then "Apply".

If you wish to support older versions of Android, you can install additional Android SDKs from this screen.
The React Native command line interface requires the ANDROID_HOME environment variable to be set up.
Create or edit your ~/.bashrc file and add the following lines:
The second line will add the android tool to your path, which will come in handy in the next step.
Please make sure you export the correct path for
ANDROID_HOMEif you did not install the Android SDK using Android Studio.
Go to Control Panel → System and Security → System → Change settings →
+Advanced System Settings → Environment variables → New, then enter the path to your Android SDK.

Please make sure you use the correct path for
ANDROID_HOMEif you did not install the Android SDK using Android Studio.
Restart the Command Prompt to apply the new environment variable.
Android Studio should have set up an Android Virtual Device for you during installation, but it is very common to run into an issue where Android Studio fails to install the AVD.

To see the list of available AVDs, launch the "AVD Manager" from within Android Studio or run the following command in a terminal:
You may follow the Android Studio User Guide to create a new AVD if needed.
If you see "No system images installed for this target." under CPU/ABI, go back to your "SDK Manager" and click on "Show Package Details" under "SDK Platforms". You will then be able to install any missing system images, such as "Google APIs Intel Atom (x86)".
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.
Use the React Native command line interface to generate a new React Native project called "AwesomeProject", then run react-native run-ios inside the newly created folder.
You should see your new app running in the iOS Simulator shortly.
react-native run-ios is just one way to run your app. You can also run it directly from within Xcode or Nuclide.
Use the React Native command line interface to generate a new React Native project called "AwesomeProject", then run react-native run-android inside the newly created folder.
If everything is set up correctly, you should see your new app running in your Android emulator shortly. react-native run-android is just one way to run your app - you can also run it directly from within Android Studio or Nuclide.
Now that you have successfully run the app, let's modify it.
index.ios.js in your text editor of choice and edit some lines.Command⌘ + R in your iOS Simulator to reload the app and see your change!index.android.js in your text editor of choice and edit some lines.R key twice or select Reload from the Developer Menu to see your change!Congratulations! You've successfully run and modified your first React Native app.

Use the React Native command line interface to generate a new React Native project called "AwesomeProject", then run react-native run-android inside the newly created folder.
If everything is set up correctly, you should see your new app running in your Android emulator shortly.
A common issue is that the packager is not started automatically when you run +
react-native run-android. You can start it manually usingreact-native start.
If you hit a
ERROR Watcher took too long to loadon Windows, try increasing the timeout in this file (under yournode_modules/react-native/).
Now that you have successfully run the app, let's modify it.
index.android.js in your text editor of choice and edit some lines.R key twice or select Reload from the Developer Menu to see your change!Congratulations! You've successfully run and modified a React Native app.

If you want to add this new React Native code to an existing application, check out the Integration guide.
If you can't get this to work, see the Troubleshooting page.
If you're curious to learn more about React Native, continue on +to the Tutorial.
You can edit the content above on GitHub and send us a pull request!
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 "🍕🍕🍕".
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 is one that controls layout, and learn about the ScrollView.
You can edit the content above on GitHub and send us a pull request!
Users interact with mobile apps mainly through touch. They can use a combination of gestures, such as tapping on a button, scrolling a list, or zooming on a map.
React Native provides components to handle common gestures, such as taps and swipes, as well as a comprehensive gesture responder system to allow for more advanced gesture recognition.
You can use "Touchable" components when you want to capture a tapping gesture. They take a function through the onPress props which will be called when the touch begins and ends within the bounds of the component.
Example:
Tappable components should provide feedback that show the user what is handling their touch, and what will happen when they lift their finger. The user should also be able to cancel a tap by dragging their finger away.
Which component you use will depend on what kind of feedback you want to provide:
Generally, you can use TouchableHighlight anywhere you would use a button or link on web. The view's background will be darkened when the user presses down on the button.
You may consider using TouchableNativeFeedback on Android to display ink surface reaction ripples that respond to the user's touch.
TouchableOpacity can be used to provide feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down.
If you need to handle a tap gesture but you don't want any feedback to be displayed, use TouchableWithoutFeedback.
In some cases, you may want to detect when a user presses and holds a view for a set amount of time. These long presses can be handled by passing a function to the onLongPress props of any of the touchable components listed above.
A common pattern to many mobile apps is the scrollable list of items. Users interact with these using panning or swiping gestures. The ScrollView component displays a list of items that can be scrolled using these gestures.
ScrollViews can scroll vertically or horizontally, and can be configured to allow paging through views using swiping gestures by using the pagingEnabled props. Swiping horizontally between views can also be implemented on Android using the ViewPagerAndroid component.
A ListView is a special kind of ScrollView that is best suited for displaying long vertical lists of items. It can also display section headers and footers, similar to UITableViews on iOS.
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.
If you want to allow a user to drag a view around the screen, or you want to implement your own custom pan/drag gesture, take a look at the PanResponder API or the gesture responder system docs.
You can edit the content above on GitHub and send us a pull request!
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.
A task is a simple async function that you register on AppRegistry, similar to registering React applications:
Then, in SomeTaskName.js:
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).
Yes, this does still require some native code, but it's pretty thin. You need to extend HeadlessJsTaskService and override getTaskConfig, e.g.:
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.
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!
A component's height and width determine its size on the screen.
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.
Setting dimensions this way is common for components that should always render at exactly the same size, regardless of screen 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
widthandheightorflex, the parent will have dimensions of 0 and theflexchildren will not be visible.
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!
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 on from +network.
You can also add style to an image:
By default, GIF and WebP are not supported on Android.
You will need to add some optional modules in android/app/build.gradle, depending on the needs of your app.
Also, if you use GIF with ProGuard, you will need to add this rule in proguard-rules.pro :
Invoked on mount and layout changes with
+{nativeEvent: {layout: {x, y, width, height}}}.
Invoked when load completes successfully.
Invoked when load either succeeds or fails.
Invoked on load start.
e.g., onLoadStart={(e) => this.setState({loading: true})}
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)
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.
Changes the color of all the non-transparent pixels to the tintColor.
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
ImageResizeModeis anEnumfor different image resizing modes, set via the +resizeModestyle property onImagecomponents. The values arecontain,cover, +stretch,center,repeat.
A unique identifier for this element to be used in UI Automation +testing scripts.
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.
The text that's read by the screen reader when the user interacts with +the image.
When true, indicates the image is an accessibility element.
blurRadius: the blur radius of the blur filter added to the image
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.
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').Invoked on load error with {nativeEvent: {error}}.
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.
Invoked on download progress with {nativeEvent: {loaded, total}}.
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.
| Name and Type | Description |
|---|---|
| uri string | The location of the image. |
| success function | The function that will be called if the image was sucessfully 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. |
Prefetches a remote image for later use by downloading it to the disk +cache
| Name and Type | Description |
|---|---|
| url string | The remote location of the image. |
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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!
As of 0.14 release, React Native provides a unified way of managing images 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:
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 file depending on the platform you are running on.
You can also use @2x, @3x, etc. suffix in the file name to provide images for different screen densities. For example, if you have the following file structure:
And button.js code contains
Packager will bundle and serve the image corresponding to device's screen density, e.g. on iPhone 5s check@2x.png will be used, on Nexus 5 – check@3x.png. 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:
Note that in order for this to work, the image name in require has to be known statically.
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.
Available React Native 0.14+. If you've generated your project with 0.13 or earlier, read this. The new asset system relies on build hooks for Xcode and Gradle that are included in new projects generated with react-native init. If you generated your projects before that, you'll have to manually add them to your projects to use the new images asset system. See Upgrading for instructions on how to do this.
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 (via Xcode asset catalogs or Android drawable folder):
Note that this approach provides 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.
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.
See CameraRoll for an example of
+using local resources that are outside of Images.xcassets.
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.
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:
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.
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.
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.
Image decoding can take more than a frame-worth of time. This is one of the major source 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!
Check if the ImageStore contains image data for the specified URI. +@platform ios
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
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
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!
This section will be updated shortly showing an integration into a more real world application such as the 2048 app that was used for Objective-C and Swift.
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 keys to integrating React Native components into your iOS application are to:
Podfile with subspecs for all the React Native components you will need for your integration.RCTRootView that points to your React Native component and its AppRegistry name that you defined in index.ios.js.react-native-xcode.sh script).The keys to integrating React Native components into your Android application are to:
react-native in your Android application root directory to create node_modules/ directory.com.facebook.react:react-native:+ and a maven pointing to the react-native binaries in node_modules/ to your build.gradle file.Activity that creates a ReactRootView.The Android Getting Started guide will install the appropriate prerequisites (e.g., npm) for React Native on the Android target platform and your chosen development environment.
To ensure a smooth experience, make sure your
androidproject is under$root/android.
First, follow the Getting Started guide for your development environment and the iOS target platform to install the prerequisites for React Native.
To ensure a smooth experience, make sure your
iOSproject is under$root/ios.
CocoaPods is a package management tool for iOS and Mac development. We use it to add the actual React Native framework code locally into your current project.
It is technically possible not to use CocoaPods, but this requires manual library and linker additions that overly complicates this process.
Assume the app for integration is a <a href="https://en.wikipedia.org/wiki/2048_(video_game)">2048</a> game. Here is what the main menu of the native application looks like without React Native.
Assume the app for integration is a <a href="https://en.wikipedia.org/wiki/2048_(video_game)">2048</a> game. Here is what the main menu of the native application looks like without React Native.

React Native integration requires both the React and React Native node modules. The React Native Framework will provide the code to allow your application integration to happen.
package.json #We will add the package dependencies to a package.json file. Create this file in the root of your project if it does not exist.
Normally with React Native projects, you will put files like
package.json,index.ios.js, etc. in the root directory of your project and then have your iOS specific native code in a subdirectory likeios/where your Xcode project is located (e.g.,.xcodeproj).
Below is an example of what your package.json file should minimally contain.
Version numbers will vary according to your needs. Normally the latest versions for both React and React Native will be sufficient.
Install the React and React Native modules via the Node package manager. The Node modules will be installed into a node_modules/ directory in the root of your project.
The React Native Framework was installed as Node module in your project above. We will now install a CocoaPods Podfile with the components you want to use from the framework itself.
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. That is where subspecs come in. When you create your Podfile, you are going to specify React Native library dependencies that you will want installed so that your application can use those libraries. Each library will become a subspec in the Podfile.
The list of supported subspecs are 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.
After you have used Node to install the React and React Native frameworks into the node_modules directory, and you have decided on what React Native elements you want to integrate, you are ready to create your Podfile so you can install those components for use in your application.
The easiest way to create a Podfile is by using the CocoaPods init command in the native iOS code directory of your project:
The Podfile will be created and saved in the iOS directory (e.g., ios/) of your current project and will contain a boilerplate setup that you will tweak for your integration purposes. In the end, Podfile should look something similar to this:
After you have created your Podfile, you are ready to install the React Native pod.
Your should see output such as:
If you get a warning such as "The
swift-2048 [Debug]target overrides theFRAMEWORK_SEARCH_PATHSbuild setting defined inPods/Target Support Files/Pods-swift-2048/Pods-swift-2048.debug.xcconfig. This can lead to problems with the CocoaPods installation", then make sure theFramework Search PathsinBuild Settingsfor bothDebugandReleaseonly contain$(inherited).
Now that we have a package foundation, we will actually modify the native application to integrate React Native into the application. For our 2048 app, we will add a "High Score" screen in React Native.
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.
index.ios.js file #First, create an empty index.ios.js file. For ease, I am doing this in the root of the project.
index.ios.jsis the starting point for React Native applications on iOS. And it is always required. It can be a small file thatrequires 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 inindex.ios.js
In your index.ios.js, create your component. In our sample here, we will add simple <Text> component within a styled <View>
RNHighScoresis the name of your module that will be used when you add a view to React Native from within your iOS application.
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 .
You can add a new link on the main game menu to go to the "High Score" React Native page.

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 library.
The
initialPropertiesare here for illustration purposes so we have some data for our high score screen. In our React Native component, we will usethis.propsto get access to that data.
Note that
RCTRootView initWithURLstarts 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, useRCTBridge initWithBundleURLto create a bridge and then useRCTRootView initWithBridge.
First import the React library.
The
initialPropertiesare here for illustration purposes so we have some data for our high score screen. In our React Native component, we will usethis.propsto get access to that data.
Note that
RCTRootView bundleURLstarts 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 usingRCTRootView bundleURL, useRCTBridge initWithBundleURLto create a bridge and then useRCTRootView initWithBridge.
When moving your app to production, the
NSURLcan point to a pre-bundled file on disk via something like[[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];. You can use thereact-native-xcode.shscript innode_modules/react-native/packager/to generate that pre-bundled file.
When moving your app to production, the
NSURLcan point to a pre-bundled file on disk via something likelet mainBundle = NSBundle(URLForResource: "main" withExtension:"jsbundle"). You can use thereact-native-xcode.shscript innode_modules/react-native/packager/to generate that pre-bundled file.
Wire up the new link in the main menu to the newly added event handler method.

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 Insideevent, drag that to the storyboard and then select the created method from the list provided.
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 packager and the server running on localhost to serve it.
Apple has blocked implicit cleartext HTTP resource loading. So we need to add the following our project's Info.plist (or equivalent) file.
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:
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:

Here is the React Native high score screen:

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.
You can examine the code that added the React Native screen on GitHub.
You can examine the code that added the React Native screen on GitHub.
In your app's root folder, run:
This creates a node module for your app and adds the react-native npm dependency. Now open the newly created package.json file and add this under scripts:
Copy & paste the following code to index.android.js in your root folder — it's a barebones React Native app:
In your app's build.gradle file add the React Native dependency:
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 fromnpm.
In your project's build.gradle file add an entry for the local React Native maven directory:
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.
Next, make sure you have the Internet permission in your AndroidManifest.xml:
If you need to access to the DevSettingsActivity add to your AndroidManifest.xml:
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.
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
AppCompatActivityclass from thecom.android.support:appcompatpackage instead ofActivity.
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.
A
ReactInstanceManagercan be shared amongst multiple activities and/or fragments. You will want to make your ownReactFragmentorReactActivityand have a singleton holder that holds aReactInstanceManager. When you need theReactInstanceManager(e.g., to hook up theReactInstanceManagerto 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:
We also need to pass back button events to React Native:
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):
That's it, your activity is ready to run some JavaScript code.
To run your app, you need to first start the development server. To do this, simply run the following command in your root folder:
Now build and run your Android app as normal (./gradlew installDebug from command-line; in Android Studio just create debug build as usual).
If you are using Android Studio for your builds and not the Gradle Wrapper directly, make sure you install watchman before running
npm start. It will prevent the packager from crashing due to conflicts between Android Studio and the React Native packager.
Once you reach your React-powered activity inside the app, it should load the JavaScript code from the development server and display:

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’ll be included with your native Android app:
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!
You can edit the content above on GitHub and send us a pull request!
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:
Compare this to other scheduling alternatives:
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:
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.
Schedule a function to run after all interactions have completed. Returns a cancellable +"promise".
Notify manager that an interaction has started.
Notify manager that an interaction has completed.
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).
You can edit the content above on GitHub and send us a pull request!
When using React Native, you're going to be running your JavaScript code in two environments:
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.
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
promise.catch(function() { });ES6
<C onPress={() => this.setState({pressed: true})}let greeting = 'hi';Math.max(...array);class C extends React.Component { render() { return <View />; } }const answer = 42;var {isActive, style} = this.props;for (var num of [1, 2, 3]) {}import React, { Component } from 'react';var key = 'abc'; var obj = {[key]: 10};var obj = { method() { return 10; } };var name = 'vjeux'; var obj = { name };function(type, ...args) { }var who = 'world'; var str = `Hello ${who}`;ES7
var extended = { ...obj, a: 10 };function f(a, b, c,) { }async function doStuffAsync() { const foo = await doOtherStuffAsync(); };Specific
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!
Keyboard component to control keyboard events.
The Keyboard component allows you to listen for native events and react to them, as +well as make changes to the keyboard, like dismissing it.
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} nativeEvent 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
@param {function} jsFunction function to be called when the event fires.
Removes all listeners for a specific event type.
@param {string} eventType The native event string listeners are watching which will be removed.
Removes a specific subscription.
@param {EmitterSubscription} subscription The subscription emitter to be removed.
Dismisses the active keyboard and removes focus.
You can edit the content above on GitHub and send us a pull request!
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.
The style of the content container(View) when behavior is 'position'.
This is the distance between the top of the user screen and the react native view, +may be non-zero in some use cases.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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 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.
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 works like border-left-width in CSS.
+See https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-width
+for more details.
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 works like border-top-width in CSS.
+See https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-width
+for more details.
borderWidth works like border-width in CSS.
+See https://developer.mozilla.org/en-US/docs/Web/CSS/border-width
+for more details.
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 logical pixel units, rather than percents, ems, or any of that.
See https://developer.mozilla.org/en-US/docs/Web/CSS/bottom
+ for more details of how bottom affects layout.
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 css-layout library
+ at https://github.com/facebook/css-layout.
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.
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.
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 sets the height of this component.
It works similarly to height in CSS, but in React Native you
+ must use logical pixel units, rather than percents, ems, or any of that.
+ See https://developer.mozilla.org/en-US/docs/Web/CSS/height for more details.
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 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 logical pixel units, rather than percents, ems, or any of that.
See https://developer.mozilla.org/en-US/docs/Web/CSS/left
+ for more details of how left affects layout.
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 works like margin-bottom in CSS.
+ See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-bottom
+ for more details.
Setting marginHorizontal has the same effect as setting
+ both marginLeft and marginRight.
marginLeft works like margin-left in CSS.
+ See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-left
+ for more details.
marginRight works like margin-right in CSS.
+ See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-right
+ for more details.
marginTop works like margin-top in CSS.
+ See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-top
+ for more details.
Setting marginVertical has the same effect as setting both
+ marginTop and marginBottom.
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 logical pixel units, rather than percents, ems, or any of that.
See https://developer.mozilla.org/en-US/docs/Web/CSS/max-height + for more details.
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 logical pixel units, rather than percents, ems, or any of that.
See https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + for more details.
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 logical pixel units, rather than percents, ems, or any of that.
See https://developer.mozilla.org/en-US/docs/Web/CSS/min-height + for more details.
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 logical pixel units, rather than percents, ems, or any of that.
See https://developer.mozilla.org/en-US/docs/Web/CSS/min-width + for more details.
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 likeoverflow` in CSS (default: visible).
+ See https://developer.mozilla.org/en/docs/Web/CSS/overflow
+ for more details.
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 works like padding-bottom in CSS.
+See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-bottom
+for more details.
Setting paddingHorizontal is like setting both of
+ paddingLeft and paddingRight.
paddingLeft works like padding-left in CSS.
+See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-left
+for more details.
paddingRight works like padding-right in CSS.
+See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-right
+for more details.
paddingTop works like padding-top in CSS.
+See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-top
+for more details.
Setting paddingVertical is like setting both of
+ paddingTop and paddingBottom.
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/css-layout
+ for more details on how position differs between React Native
+ and CSS.
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 logical pixel units, rather than percents, ems, or any of that.
See https://developer.mozilla.org/en-US/docs/Web/CSS/right
+ for more details of how right affects layout.
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 logical pixel units, rather than percents, ems, or any of that.
See https://developer.mozilla.org/en-US/docs/Web/CSS/top
+ for more details of how top affects layout.
width sets the width of this component.
It works similarly to width in CSS, but in React Native you
+ must use logical pixel units, rather than percents, ems, or any of that.
+ See https://developer.mozilla.org/en-US/docs/Web/CSS/width for more details.
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.
You can edit the content above on GitHub and send us a pull request!
Automatically animates views to their new positions when the +next layout happens.
A common way to use this API is to call LayoutAnimation.configureNext
+before calling setState.
Schedules an animation to happen on the next layout.
@param config Specifies animation properties:
duration in millisecondscreate, 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.
Helper for creating a config for configureNext.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
Install a library with native dependencies:
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.
Link your native dependencies:
Done! All libraries with a native dependencies should be successfully linked to your iOS/Android project.
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);

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

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!
Linking gives you a general interface to interact with both incoming
+and outgoing app 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
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.
NOTE: On iOS you'll need to link RCTLinking to your project by following
+the steps described here.
+In case you also want to listen to incoming app links during your app's
+execution you'll need to add the following lines to you *AppDelegate.m:
And then on your React component you'll be able to listen to the events on
+Linking as follows
To start the corresponding activity for a link (web URL, email, contact etc.), call
If you want to check if any installed app can handle a given URL beforehand you can call
Add a handler to Linking changes by listening to the url event type
+and providing the handler
Remove a handler by passing the url event type and the handler
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"), a contact, +or any other URL that can be opened with the installed apps.
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!
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
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!
Examples # | Edit on GitHub |
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:
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.
An instance of ListView.DataSource to use
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.
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.
(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.
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.
Threshold in pixels (virtual, not physical) for calling onEndReached.
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.
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.
() => 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.
(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).
(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.
(sectionData, sectionID) => renderable
If provided, a sticky header is rendered for this section. 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.
(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.
How early to start rendering rows before they come on screen, in +pixels.
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}.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
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:
or
or
The constructor takes in a params argument that can contain any of the +following:
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.
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!
Returns if the row is dirtied and needs to be rerendered
Gets the data required to render the row.
Gets the rowID at index provided if the dataSource arrays were flattened, +or null of out of range indexes.
Gets the sectionID at index provided if the dataSource arrays were flattened, +or null for out of range indexes.
Returns an array containing the number of rows in each section
Returns if the section header is dirtied and needs to be rerendered
Gets the data required to render the section header
You can edit the content above on GitHub and send us a pull request!
This component is only supported on iOS.
MapView is used to display embeddable maps and annotations using
+MKMapView.
For a cross-platform solution, check out +react-native-maps +by Airbnb.
Map annotations with title and subtitle.
If true the map will follow the user's location whenever it changes.
+Note that this has no effect unless showsUserLocation is enabled.
+Default value is true.
Insets for the map's legal label, originally at bottom left of the map.
The map type to be displayed.
standard: Standard road map (default).satellite: Satellite view.hybrid: Satellite view with roads and points of interest overlaid.Maximum size of the area that can be displayed.
Minimum size of the area that can be displayed.
Deprecated. Use annotation onFocus and onBlur instead.
Callback that is called continuously when the user is dragging the map.
Callback that is called once, when the user is done moving the map.
Map overlays
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.
The region to be displayed by the map.
The region is defined by the center coordinates and the span of +coordinates to display.
When this property is set to true and a valid camera is associated with
+the map, the camera's heading angle is used to rotate the plane of the
+map around its center point.
When this property is set to false, the
+camera's heading angle is ignored and the map is always oriented so
+that true north is situated at the top of the map view
If false the user won't be able to change the map region being displayed.
+Default value is true.
If false, compass won't be displayed on the map.
+Default value is true.
If false points of interest won't be displayed on the map.
+Default value is true.
If true the app will ask for the user's location and display it on
+the map. Default value is false.
NOTE: You'll need to add the NSLocationWhenInUseUsageDescription
+key in Info.plist to enable geolocation, otherwise it will fail silently.
Used to style and layout the MapView.
If false the user won't be able to pinch/zoom the map.
+Default value is true.
State an annotation on the map.
| Value | Description |
|---|---|
| idle | Annotation is not being touched. |
| starting | Annotation dragging has began. |
| dragging | Annotation is being dragged. |
| canceling | Annotation dragging is being canceled. |
| ending | Annotation dragging has ended. |
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
DeprecatedUse the animationType prop instead.
The animationType prop controls how the modal animates.
slide slides in from the bottomfade fades into viewnone appears without an animationThe onRequestClose prop allows passing a function that will be called once the modal has been dismissed.
On the Android platform, this is a required function.
The onShow prop allows passing a function that will be called once the modal has been shown.
The transparent prop determines whether your modal will fill the entire view. Setting this to true will render the modal over a transparent background.
The visible prop determines whether your modal is visible.
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.
The supportedOrientations prop allows the modal to be rotated to any of the specified orientations.
+On iOS, the modal is still restricted by what's specified in your app's Info.plist's UISupportedInterfaceOrientations field.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
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.
There are a lot of example apps at the React Native Playground. You can see the code running on a real device, which is a neat feature.
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.
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.
Exponent is a development environment plus application that focuses on letting you build React Native apps in the Exponent development environment, without ever touching Xcode or Android Studio. If you wish React Native was even more JavaScripty and webby, check out Exponent.
Deco is an all-in-one development environment specifically designed for React Native. It can automatically set up a new project, search for open source components, and insert them. You can also tweak your app graphically in real time. Check it out if you use macOS.
The React Native Community Facebook group has thousands of developers, and it's pretty active. Come there to show off your project, or ask how other people solved similar problems.
Reactiflux is a Discord chat where a lot of React-related discussion happens, including React Native. Discord is just like Slack except it works better for open source projects with a zillion contributors. Check out the #react-native channel.
The React Twitter account covers both React and React Native. Follow the React Native Twitter account and blog to find out what's happening in the world of React Native.
There are a lot of React Native Meetups that happen around the world. Often there is React Native content in React meetups as well.
Sometimes we have React conferences. We posted the videos from React.js Conf 2016, and we'll probably have more conferences in the future, too. Stay tuned.
You can edit the content above on GitHub and send us a pull request!
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.
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:
createViewInstance method@ReactProp (or @ReactPropGroup) annotationcreateViewManagers of the applications package.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.
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.
@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).
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.
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.
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.
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.
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:
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!
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.
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:
RCT_EXPORT_MODULE() marker macro.-(UIView *)view method.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.
Then you just need a little bit of JavaScript to make this a usable React component:
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 :(
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:
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:
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:
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:
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:
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:
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.
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 RCTMapManager, 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):
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:
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:
The RCTDatePickerIOSConsts constants are exported from native by grabbing the actual frame of the native component like so:
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!
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.
If you plan to make changes in Java code, we recommend enabling Gradle Daemon to speed up builds.
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.
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.
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.
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).
The following argument types are supported for methods annotated with @ReactMethod and they directly map to their JavaScript equivalents
Read more about ReadableMap and ReadableArray
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.
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.
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.
Now, from your other JavaScript file you can call the method like this:
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.
This method would be accessed in JavaScript using:
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.
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:
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:
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.
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.
JavaScript modules can then register to receive events by addListenerOn using the Subscribable mixin
You can also directly use the DeviceEventEmitter module to listen for events.
startActivityForResult #You'll need to listen to onActivityResult if you want to get results from an activity you started with startActivityForResult. To do this, the 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,
Now you can listen to onActivityResult by implementing the following method:
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.
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,
Now you can listen to the activity's LifeCycle events by implementing the following methods:
You can edit the content above on GitHub and send us a pull request!
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).
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.
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.
React Native will not expose any methods of CalendarManager to JavaScript unless explicitly told to. This is done using the RCT_EXPORT_METHOD() macro:
Now, from your JavaScript file you can call the method like this:
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).
RCT_EXPORT_METHOD supports all standard JSON object types, such as:
NSString)NSInteger, float, double, CGFloat, NSNumber)BOOL, NSNumber)NSArray) of any types from this listNSDictionary) with string keys and values of any type from this listRCTResponseSenderBlock)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:
or like this:
But by using the automatic type conversion feature, we can skip the manual conversion step completely, and just write:
You would then call this from JavaScript by using either:
or
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:
and call it from JavaScript:
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
NSArraycontaining a mix ofNSNumberandNSString. For arrays,RCTConvertprovides some typed collections you can use in your method declaration, such asNSStringArray, orUIColorArray. For maps, it is the developer's responsibility to check the value types individually by manually callingRCTConverthelper methods.
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.
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.
A native module is supposed to invoke its callback only once. It can, however, 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 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.
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:
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:
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:
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 it's own queue so the React queue isn't blocked waiting on potentially slow disk access:
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:
NOTE: Sharing dispatch queues between modules
The
methodQueuemethod 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.
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 RTCBridgeDelegate Protocol, initializing an RTCBridge with the delegate as an argument and initialising a RTCRootView with the initialized bridge.
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.
JavaScript can use this value right away, synchronously:
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.
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:
You must create a class extension of RCTConvert like so:
You can then define methods and export your enum constants like this:
Your enum will then be automatically unwrapped using the selector provided (integerValue in the above example) before being passed to your exported method.
The native module can signal events to JavaScript without being invoked directly. The easiest way to do this is to use eventDispatcher:
JavaScript code can subscribe to these events:
For more examples of sending events to JavaScript, see RCTLocationObserver.
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:
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:
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.
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!
NativeMethodsMixin provides methods to access the underlying native
+component directly. This can be useful in cases when you want to focus
+a view or measure its on-screen dimensions, for example.
The methods described here are available on most of the default components +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. For more +information, see Direct +Manipulation.
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:
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.
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:
Note that these measurements are not available until after the rendering +has been completed in native.
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
+React.findNodeHandle(component).
Requests focus for the given input or view. The exact behavior triggered +will depend on the platform and type of view.
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!
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 Navigator. If you are only targeting iOS and would like to stick to the native look and feel, check out NavigatorIOS. If you are looking for greater control over your navigation stack, you can't go wrong with NavigationExperimental.
Navigator provides a JavaScript implementation of a navigation stack, so it works on both iOS and Android and is easy to customize. This is the same component you used to build your first navigation stack in the navigators tutorial.

Navigator can easily be adapted to render different components based on the current route in its renderScene function. It will transition new scenes onto the screen by sliding in from the right by default, but you can control this behavior by using the configureScene function. You can also configure a navigation bar through the navigationBar prop.
Check out the Navigator API reference for specific examples that cover each of these scenarios.
If you are targeting iOS only, you may also want to consider using NavigatorIOS. It looks and feels just like UINavigationController, because it is actually built on top of it.

Just like Navigator, NavigatorIOS uses routes to represent scenes, 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.
Check out the NavigatorIOS reference docs to learn more about this component.
You may also want to check out react-native-navigation, a component that aims to provide native navigation on both iOS and Android.
Navigator and NavigatorIOS are both stateful components. If your app has multiple of these, it can become tricky to coordinate navigation transitions between them. NavigationExperimental provides a different approach to navigation, allowing any view to act as a navigation view and using reducers to manipulate state at a top-level object. It is bleeding edge as the name implies, but you might want to check it out if you are craving greater control over your app's navigation.
You can import NavigationExperimental like any other component in React Native. Once you have that, you can deconstruct any additional components from NavigationExperimental that you may find useful. Since I am feeling like building navigation stacks today, I'll go ahead and pick out NavigationCardStack and NavigationStateUtils.
As I said earlier, NavigationExperimental takes a different approach than Navigator and NavigatorIOS. Using it to build a navigation stack requires a few more steps than the stateful components, but the payoff is worth it.
Create a new component for your application. This will be the top-level object, so we will define the initial state here. The navigation state will be defined in the navigationState key, where we define our initial route:
Alright, now we have a simple stateful component that doesn't do much at all. We can change that. Our initial state contains one route, and the current index. That looks suspiciously just like our initial route definition in Navigator. Do you remember which actions its navigator object provided?
Push and pop, of course. That seems pretty straightforward to implement. I promised you earlier we would be using reducers to manage state at the top-level object. Sit tight.
NavigationExperimental comes built-in with a some useful reducers, and they are all available as part of NavigationStateUtils. The two we will be using right now are called -- yep -- push and pop. They take a navigationState object, and return a new navigationState object.
We can use them to write our _onNavigationChange function which, given a "push" or "pop" action, will reduce the state accordingly.
Cool. I'm getting the hang of this. This is the heart of NavigationExperimental. We are only handling two actions here, but a more complex application could also take into account a "back" action (e.g. Android back button), as well as handle the transition between several tabs in a tabbed application.
I am still missing the initial scene that will be rendered (as well as the actual navigator that will wrap it, but let's not get ahead of ourselves).
First I want to define a Row component out of convenience. It displays some text and can call some function when pressed.
Now I will define my actual scene. It uses a scroll view to display a vertical list of items. The first row displays the current route's key, and two more rows will call our theoretical navigator's push and pop functions.
Now that I have defined the state and a function to manage it, I think I can go ahead and create a proper navigator component now. While I'm at it, I'll render my scene after configuring it with the current route's props.
That's it -- so close to the finish line I can smell it. Let's plug our new navigator into our top-level component:
We're done! Bask in the glory of NavigationExperimental.
(Oh yes, sorry about that -- here's our missing imports and styles.)
You are now an expert navigator. Take a look at NavigationExperimental in UIExplorer to learn how to implement other types of navigation hierarchies, such as a tabbed application with multiple navigation stacks.
You can edit the content above on GitHub and send us a pull request!
Navigator handles the transition between different scenes in your app.
+It is implemented in JavaScript and is available on both iOS and Android. If
+you are targeting iOS only, you may also want to consider using
+NavigatorIOS as it leverages native UIKit
+navigation.
To set up the Navigator you provide one or more objects called routes,
+to identify each scene. You also provide a renderScene function that
+renders the scene for each route object.
In the above example, initialRoute is used to specify the first route. It
+contains a title property that identifies the route. The renderScene
+prop returns a function that displays text based on the route's title.
The first example demonstrated one scene. To set up multiple scenes, you pass
+the initialRouteStack prop to Navigator:
In the above example, a routes variable is defined with two route objects
+representing two scenes. Each route has an index property that is used to
+manage the scene being rendered. The renderScene method is changed to
+either push or pop the navigator depending on the current route's index.
+Finally, the Text component in the scene is now wrapped in a
+TouchableHighlight component to help trigger the navigator transitions.
You can optionally pass in your own navigation bar by returning a
+Navigator.NavigationBar component to the navigationBar prop in
+Navigator. You can configure the navigation bar properties, through
+the routeMapper prop. There you set up the left, right, and title
+properties of the navigation bar:
When configuring the left, right, and title items for the navigation bar, +you have access to info such as the current route object and navigation +state. This allows you to customize the title for each scene as well as +the buttons. For example, you can choose to hide the left button for one of +the scenes.
Typically you want buttons to represent the left and right buttons. Building +on the previous example, you can set this up as follows:
This sets up a left navigator bar button that's visible on scenes after the +the first one. When the button is tapped the navigator is popped.
Another type of navigation bar, with breadcrumbs, is provided by
+Navigator.BreadcrumbNavigationBar. You can also provide your own navigation
+bar by passing it through the navigationBar prop. See the
+UIExplorer
+demo to try out both built-in navigation bars out and see how to use them.
To change the animation or gesture properties of the scene, provide a
+configureScene prop to get the config object for a given route:
In the above example, the newly pushed scene will float up from the bottom.
+See Navigator.SceneConfigs for default animations and more info on
+available scene config options.
Optional function where you can configure scene animations and
+gestures. Will be invoked with route and routeStack parameters,
+where route corresponds to the current scene being rendered by the
+Navigator and routeStack is the set of currently mounted routes
+that the navigator could transition to.
The function should return a scene configuration object.
Available scene configuration options are:
The initial route for navigation. A route is an object that the navigator +will use to identify each scene it renders.
If both initialRoute and initialRouteStack props are passed to
+Navigator, then initialRoute must be in a route in
+initialRouteStack. If initialRouteStack is passed as a prop but
+initialRoute is not, then initialRoute will default internally to
+the last item in initialRouteStack.
Pass this in to provide a set of routes to initially mount. This prop
+is required if initialRoute is not provided to the navigator. If this
+prop is not passed in, it will default internally to an array
+containing only initialRoute.
Use this to provide an optional component representing a navigation bar
+that is persisted across scene transitions. This component will receive
+two props: navigator and navState representing the navigator
+component and its state. The component is re-rendered when the route
+changes.
Optionally pass in the navigator object from a parent Navigator.
Will be called with the new route of each scene after the transition is +complete or after the initial mounting.
Pass in a function to get notified with the target route when +the navigator component is mounted and before each navigator transition.
Required function which renders the scene for a given route. Will be
+invoked with the route and the navigator object.
Styles to apply to the container of each scene.
Reset every scene with an array of routes.
| Name and Type | Description |
|---|---|
| nextRouteStack RouteStack | Next route stack to reinitialize. +All existing route stacks are destroyed an potentially recreated. There +is no accompanying animation and this method immediately replaces and +re-renders the navigation bar and the stack items. |
Transition to an existing scene without unmounting.
| Name and Type | Description |
|---|---|
| route object | Route to transition to. The specified route must
+be in the currently mounted set of routes defined in |
Jump forward to the next scene in the route stack.
Jump backward without unmounting the current scene.
Navigate forward to a new scene, squashing any scenes that you could +jump forward to.
| Name and Type | Description |
|---|---|
| route object | Route to push into the navigator stack. |
Go back N scenes at once. When N=1, behavior matches pop().
+When N is invalid(negative or bigger than current routes count), do nothing.
| Name and Type | Description |
|---|---|
| n number | The number of scenes to pop. Should be an integer. |
Transition back and unmount the current scene.
Replace a scene as specified by an index.
| Name and Type | Description |
|---|---|
| route object | Route representing the new scene to render. |
| index number | The route in the stack that should be replaced. + If negative, it counts from the back of the stack. |
| cb Function | Callback function when the scene has been replaced. |
Replace the current scene with a new route.
| Name and Type | Description |
|---|---|
| route object | Route that replaces the current scene. |
Replace the previous scene.
| Name and Type | Description |
|---|---|
| route object | Route that replaces the previous scene. |
Pop to the first scene in the stack, unmounting every other scene.
Pop to a particular scene, as specified by its route. +All scenes after it will be unmounted.
| Name and Type | Description |
|---|---|
| route object | Route to pop to. |
Replace the previous scene and pop to it.
| Name and Type | Description |
|---|---|
| route object | Route that replaces the previous scene. |
Navigate to a new scene and reset route stack.
| Name and Type | Description |
|---|---|
| route object | Route to navigate to. |
Returns the current list of routes.
You can edit the content above on GitHub and send us a pull request!
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
+Navigator for a similar solution for your
+cross-platform needs, or check out
+react-native-navigation, a
+component that aims to provide native navigation on both iOS and Android.
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.
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:
You can then access the props passed in via {this.props.myProp}.
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:
You can also trigger navigator functionality from the NavigatorIOS
+component:
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.
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.
In the example above the navigation bar color is changed when the new route +is pushed.
The default background color of the navigation bar.
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.
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.
The default wrapper style for components in the navigator.
+A common use case is to set the backgroundColor for every scene.
Boolean value that indicates whether the navigation bar is hidden +by default.
Boolean value that indicates whether to hide the 1px hairline shadow +by default.
The default color used for the buttons in the navigation bar.
The default text color of the navigation bar title.
Boolean value that indicates whether the navigation bar is +translucent by default
Navigate forward to a new route.
| Name and Type | Description |
|---|---|
| route object | The new route to navigate to. |
Go back N scenes at once. When N=1, behavior matches pop().
| Name and Type | Description |
|---|---|
| n number | The number of scenes to pop. |
Pop back to the previous scene.
Replace a route in the navigation stack.
| Name and Type | Description |
|---|---|
| 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 the route for the current scene and immediately +load the view for the new route.
| Name and Type | Description |
|---|---|
| route object | The new route to navigate to. |
Replace the route/view for the previous scene.
| Name and Type | Description |
|---|---|
| route object | The new route to will replace the previous scene. |
Go back to the topmost item in the navigation stack.
Go back to the item for a particular route object.
| Name and Type | Description |
|---|---|
| route object | The new route to navigate to. |
Replaces the previous route/view and transitions back to it.
| Name and Type | Description |
|---|---|
| route object | The new route that replaces the previous scene. |
Replaces the top item and pop to it.
| Name and Type | Description |
|---|---|
| route object | The new route that will replace the topmost item. |
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
NetInfo exposes info about online/offline status
Asynchronously determine if the device is online and on a cellular network.
none - device is offlinewifi - device is online and connected via wifi, or is the iOS simulatorcell - device is connected via Edge, 3G, WiMax, or LTEunknown - error case and the network status is unknownTo 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 offlineBLUETOOTH - 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 21WIFI - 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.
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.
Available on all platforms. Asynchronously fetch a boolean to determine +internet connectivity.
Invokes the listener whenever network status changes. +The listener receives one of the connectivity types listed above.
Removes the listener for network status changes.
Returns a promise that resolves with one of the connectivity types listed +above.
An object with the same methods as above but the listener receives a +boolean which represents the internet connectivity. +Use this if you are only interested with whether the device has internet +connectivity.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
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.
In order to fetch content from an arbitrary URL, just pass the URL to fetch:
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:
Take a look at the Fetch Request docs for a full list of properties.
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:
You can also use the proposed ES2017 async/await syntax in a React Native app:
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. See Apple's documentation for more information.
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.
The security model for XMLHttpRequest is different than on web as there is no concept of CORS in native apps.
React Native also supports WebSockets, a protocol which provides full-duplex communication channels over a single TCP connection.
Your app can now display all sorts of data and you may soon need to organize this content into several screens. To manage the transition between these screens, you will need to learn about navigators.
You can edit the content above on GitHub and send us a pull request!
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:
A native event is a synthetic touch event with the following form:
nativeEventchangedTouches - Array of all touch events that have changed since the last eventidentifier - The ID of the touchlocationX - The X position of the touch, relative to the elementlocationY - The Y position of the touch, relative to the elementpageX - The X position of the touch, relative to the root elementpageY - The Y position of the touch, relative to the root elementtarget - The node id of the element receiving the touch eventtimestamp - A time identifier for the touch, useful for velocity calculationtouches - Array of all current touches on the screenA gestureState object has the following:
stateID - ID of the gestureState- persisted as long as there at least
+ one touch on screenmoveX - the latest screen coordinates of the recently-moved touchmoveY - the latest screen coordinates of the recently-moved touchx0 - the screen coordinates of the responder granty0 - the screen coordinates of the responder grantdx - accumulated distance of the gesture since the touch starteddy - accumulated distance of the gesture since the touch startedvx - current velocity of the gesturevy - current velocity of the gesturenumberActiveTouches - Number of touches currently on screenTo see it in action, try the +PanResponder example in UIExplorer
@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!
Examples # | Edit on GitHub |
A compelling reason for using React Native instead of WebView-based +tools is to achieve 60 FPS and a native look & 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.
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.
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.
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.
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.
+(Read about why you should probably use Navigator
+anyways.
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 though, +but their receipt is not necessary for the scroll to occur).
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.
There is a babel plugin that can remove all
console.*calls. You need to install it first usingnpm install babel-plugin-transform-remove-console --save, and then edit (or create).babelrcunder your project directory like the following:{ + "env": { + "production": { + "plugins": ["transform-remove-console"] + } + } +}Then it will automatically remove all
console.*calls in a release (production) version of your project. However, theconsole.*calls will still be executed in the debug version of your project.
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.
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.
Part of the long-term 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.
Unfortunately this solution is not yet implemented, and so in the
+meantime we should use the InteractionManager to selectively render the
+minimal amount of content necessary for the new scene as long as the
+animation is in progress. InteractionManager.runAfterInteractions takes
+a callback as its only argument, and that callback is fired when the
+navigator transition is complete (each animation from the Animated API
+also notifies the InteractionManager, but that's beyond the scope of
+this discussion).
Your scene component might look something like this:
You don't need to be limited to rendering some loading indicator, you +could alternatively render part of your content -- for example, when you +load the Facebook app you see a placeholder news feed item with grey +rectangles where text will be. If you are rendering a Map in your new +scene, you might want to display a grey placeholder view or a spinner +until the transition is complete as this can actually cause frames to be +dropped on the main thread.
This is an issue that comes up frequently because iOS ships with +UITableView which gives you very good performance by re-using underlying +UIViews. Work is in progress to do something similar with React Native, +but until then we have some tools at our disposal to help us tweak the +performance to suit our needs. It may not be possible to get all the way +there, but a little bit of creativity and experimentation with these +options can go a long way.
This prop specifies how many rows we want to render on our first render
+pass. If we are concerned with getting something on screen as quickly
+as possible, we could set the initialListSize to 1, and we'll quickly
+see other rows fill in on subsequent frames. The number of rows per
+frame is determined by the pageSize.
After the initial render where initialListSize is used, ListView looks
+at the pageSize to determine how many rows to render per frame. The
+default here is 1 -- but if your views are very small and inexpensive to
+render, you might want to bump this up. Tweak it and find what works for
+your use case.
"How early to start rendering rows before they come on screen, in pixels."
If we had a list with 2000 items and rendered them all immediately that +would be a poor use of both memory and computational resources. It would +also probably cause some pretty awful jank. So the scrollRenderAhead +distance allows us to specify how far beyond the current viewport we +should continue to render rows.
"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."(The default value is false before version 0.14-rc).
This is an extremely important optimization to apply on large ListViews.
+On Android the overflow value is always hidden so you don't need to
+worry about setting it, but on iOS you need to be sure to set overflow:
+hidden on row containers.
It's common at first to overlook ListView, but using it properly is +often key to achieving solid performance. As discussed above, it +provides you with a set of tools that lets you split rendering of your +view across various frames and tweak that behavior to fit your specific +needs. Remember that ListView can be horizontal too.
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.
"Slow Navigator transitions" is the most common manifestation of this, +but there are other times this can happen. Using InteractionManager can +be a good approach, but if the user experience cost is too high to delay +work during an animation, then you might want to consider +LayoutAnimation.
The Animated api currently calculates each keyframe on-demand on the +JavaScript thread, while LayoutAnimation leverages Core Animation and is +unaffected by JS thread and main thread frame drops.
One case where I have used this is for animating in a modal (sliding +down from top and fading in a translucent overlay) while +initializing and perhaps receiving responses for several network +requests, rendering the contents of the modal, and updating the view +where the modal was opened from. See the Animations guide for more +information about how to use LayoutAnimation.
Caveats: +- LayoutAnimation only works for fire-and-forget animations ("static" + animations) -- if it must be be interruptible, you will need to use +Animated.
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.
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.
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:
Use the built-in Profiler to get detailed information about work done in +the JavaScript thread and main thread side-by-side.
For iOS, Instruments are an invaluable tool, and on Android you should +learn to use systrace.
You can edit the content above on GitHub and send us a pull request!
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 checkPermission and requestPermission
+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.
Returns a promise resolving to a boolean value as to whether the specified +permissions has been granted
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
You can edit the content above on GitHub and send us a pull request!
Renders the native picker component on iOS and Android. Example:
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
Value matching value of one of the items. Can be a string or an integer.
Used to locate this view in end-to-end tests.
If set to false, the picker will be disabled, i.e. the user will not be able to make a +selection.
On Android, specifies how to display the selection items when the user taps on the picker:
Prompt string for this picker, used on Android in dialog mode as the title of the dialog.
Style to apply to each of the item labels.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
PixelRatio class gives access to the device pixel density.
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.
Returns the device pixel density. Some examples:
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
Converts a layout size (dp) to pixel size (px).
Guaranteed to return an integer number.
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.
// 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!
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!
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:
Platform module.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.
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.
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.
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:
On Android, the Platform module can also be used to detect the version of the Android Platform in which the app is running:
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:
You can then require the component as follows:
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!
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:
If the progress bar will show indeterminate progress. Note that this +can only be false if styleAttr is Horizontal.
The progress value (between 0 and 1).
Style of the ProgressBar. One of:
Used to locate this view in end-to-end tests.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
Use ProgressViewIOS to render a UIProgressView on iOS.
The progress value (between 0 and 1).
A stretchable image to display as the progress bar.
The tint color of the progress bar itself.
The progress bar style.
A stretchable image to display behind the progress bar.
The tint color of the progress bar track.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
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:
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!
Handle push notifications for your app, including permission handling and +icon badge number.
To get up and running, configure your notifications with Apple +and your server-side system. To get an idea, this is the Parse guide.
Manually link the PushNotificationIOS library
node_modules/react-native/Libraries/PushNotificationIOS/RCTPushNotification.xcodeprojLink Binary With Libraries: libRCTPushNotification.aHeader Search Paths:
+$(SRCROOT)/../node_modules/react-native/Libraries/PushNotificationIOS and set the search to recursiveFinally, to enable support for notification and register events you need to augment your AppDelegate.
At the top of your AppDelegate.m:
#import "RCTPushNotificationManager.h"
And then in your AppDelegate implementation add the following:
Schedules the localNotification for immediate presentation.
details is an object containing:
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).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. The default value of this property is 0, which means that no badge is displayed.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).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.Cancels all scheduled localNotifications
Sets the badge number for the app icon on the home screen
Gets the current badge number for the app icon on the home screen
Cancel local notifications.
Optionally restricts the set of canceled notifications to those
+notifications whose userInfo fields match the corresponding fields
+in the userInfo argument.
Gets the local notifications that are currently scheduled.
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}.Removes the event listener. Do this in componentWillUnmount to prevent
+memory leaks
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:
alertbadgesoundIf 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.
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.
See what push permissions are currently enabled. callback will be
+invoked with a permissions object:
alert :booleanbadge :booleansound :booleanThis method returns a promise that resolves to either the notification
+object if the app was launched by a push notification, or null otherwise.
You will never need to instantiate PushNotificationIOS yourself.
+Listening to the notification event and invoking
+getInitialNotification is sufficient
An alias for getAlert to get the notification's main message string
Gets the sound string from the aps object
Gets the notification's main message from the aps object
Gets the badge count number from the aps object
Gets the data object on the notif
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
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.
Called when the view starts refreshing.
Whether the view should be indicating an active refresh.
Whether the pull to refresh functionality is enabled.
Progress view top offset
Size of the refresh indicator, see RefreshControl.SIZE.
The title displayed under the refresh indicator.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
You'll need this in order to install your app on your device. First, make sure you have USB debugging enabled on your device.
Check that your device has been successfully connected by running adb devices:
Seeing device in the right column means the device is connected. Android - go figure :) You must have only one device connected.
Now you can use react-native run-android to install and launch your app on the device. If you get a "bridge configuration isn't available" error, see the Using adb reverse section below.
Let's now set up an Android device to run our React Native projects.
First thing is to plug in your device and check the manufacturer code by using lsusb (on mac, you must first install lsusb). lsusb should output something like this:
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:
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:
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 using adb devices.
You can also iterate quickly on device using the development server. Follow one of the steps described below to make your development server running on your laptop accessible for your device.
Hint
Most modern android devices don't have a hardware menu button, which we use to trigger the developer menu. In that case you can shake the device to open the dev menu (to reload, debug, etc.). Alternatively, you can run the command
adb shell input keyevent 82to open the dev menu (82 being the Menu key code).
Note that this option is available on devices running android 5.0+ (API 21).
Have your device connected via USB with debugging enabled (see paragraph above on how to enable USB debugging on your device).
adb reverse tcp:8081 tcp:8081Reload JS and other development options with no extra configurationLaunch the packager manually with react-native start --port [PORT]
For Android: Use the developer menu by clicking the menu button or shake. Select 'Debug server host & port for device' to set a different port.
+
+
+For IOS: Edit the AppDelegate.m and change the line below to match the port number you're running:
jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
adb shell input keyevent 82 from the command line.Dev Settings.Debug server host for device.ipconfig to find your machine's IP address (more info).Reload JS.You can edit the content above on GitHub and send us a pull request!
Running an iOS app on a device requires only an Apple ID and a Mac. This guide covers only React Native specific topics.
You can iterate quickly on device using the development server. First, ensure that you are on the same Wi-Fi network as your computer.
In Xcode, select your phone as build target and press "Build and run"
Hint
Shake the device to open the developer menu.
You have built a great app using React Native, and you are now itching to release it in the App Store. The process is the same as any other native iOS app, with some additional considerations to take into account.
Building an app for distribution in the App Store requires using the Release scheme in Xcode. To do this, go to Product -> Scheme -> Edit Scheme (cmd + <), make sure you're in the Run tab from the side, and set the Build Configuration dropdown to release.
Apps built for Release will automatically disable the in-app developer menu, which will prevent your users from inadvertently accessing the menu in production. It will also load the JavaScript locally, so you can put the app on a device and test whilst not connected to the computer.
Once built for release, you'll be able to distribute the app to beta testers and submit the app to the App Store.
App Transport Security is a security feature, added in iOS 9, that rejects all HTTP requests that are not sent over HTTPS. This can result in HTTP traffic being blocked, including the developer React Native server.
ATS is disabled by default in projects generated using the React Native CLI in order to make development easier. You should re-enable ATS prior to building your app for production by removing the NSAllowsArbitraryLoads entry from your Info.plist file in the ios/ folder.
To learn more about how to configure ATS on your own Xcode projects, see this post on ATS.
You can edit the content above on GitHub and send us a pull request!
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.
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!
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.
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 + } + });
When true, the scroll view's children are arranged horizontally in a row +instead of vertically in a column. The default value is false.
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'.
When false, tapping outside of the focused text input when the keyboard +is up dismisses the keyboard. When true, the keyboard will not dismiss +automatically, and the scroll view will not catch taps, but children of +the scroll view can catch taps. The default value is false.
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.
Fires at most once per frame during scrolling. The frequency of the
+events can be controlled using the scrollEventThrottle prop.
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.
A RefreshControl component, used to provide pull-to-refresh +functionality for the ScrollView.
See RefreshControl.
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.
When false, the content does not scroll. +The default value is true.
When true, shows a horizontal scroll indicator. +The default value is true.
When true, shows a vertical scroll indicator. +The default value is true.
(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.
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.
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.
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.
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.
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.
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.
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.
When false, once tracking starts, won't try to drag if the touch moves. +The default value is true.
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.
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}.
Used to manually set the starting scroll offset.
+The default value is {x: 0, y: 0}.
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
When true, the ScrollView will try to lock to only vertical or horizontal +scrolling while dragging. The default value is false.
The style of the scroll indicators.
+ - default (the default), same as black.
+ - black, scroll indicator is black. This style is good against a white content background.
+ - white, scroll indicator is white. This style is good against a black content background.
The maximum allowed zoom scale. The default value is 1.0.
The minimum allowed zoom scale. The default value is 1.0.
Called when a scrolling animation ends.
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.
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}.
When true, the scroll view scrolls to top when the status bar is tapped. +The default value is true.
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)
When set, causes the scroll view to stop at multiples of the value of
+snapToInterval. This can be used for paginating through children
+that have lengths smaller than the scroll view. Used in combination
+with snapToAlignment.
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}.
The current scale of the scroll view content. The default value is 1.0.
Scrolls to a given x, y offset, either immediately or with a smooth animation.
Syntax:
scrollTo(options: {x: number = 0; y: number = 0; animated: boolean = true})
Note: The weird argument signature is due to the fact that, for historical reasons, +the function also accepts separate arguments as as alternative to the options object. +This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.
Deprecated, do not use.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
Use SegmentedControlIOS to render a UISegmentedControl iOS.
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.
If false the user won't be able to interact with the control. +Default value is true.
If true, then selecting a segment won't persist visually.
+The onValueChange callback will still work as expected.
Callback that is called when the user taps a segment; +passes the event as an argument
Callback that is called when the user taps a segment; +passes the segment's value as an argument
The index in props.values of the segment to be (pre)selected.
Accent color of the control.
The labels for the control's segment buttons, in order.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
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.
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.
my-release-key.keystore file under the android/app directory in your project folder.~/.gradle/gradle.properties and add the following (replace ***** with the correct keystore password, alias and 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.
Edit the file android/app/build.gradle in your project folder and add the signing config,
Simply run the following in a terminal:
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.
Before uploading the release build to the Play Store, make sure you test it thoroughly. Install it on the device using:
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 and framework JavaScript code is bundled in the APK's assets.
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:
You can edit the content above on GitHub and send us a pull request!
A component used to select a single value from a range of values.
If true the user won't be able to move the slider. +Default value is false.
Initial maximum value of the slider. Default value is 1.
Initial minimum value of the slider. Default value is 0.
Callback called when the user finishes changing the value (e.g. when +the slider is released).
Callback continuously called while the user is dragging the slider.
Step value of the slider. The value should be +between 0 and (maximumValue - minimumValue). +Default value is 0.
Used to style and layout the Slider. See StyleSheet.js and
+ViewStylePropTypes.js for more info.
Used to locate this view in UI automation tests.
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.
Assigns a maximum track image. Only static images are supported. The +leftmost pixel of the image will be stretched to fill the track.
The color used for the track to the right of the button. Overrides the +default blue gradient image.
Assigns a minimum track image. Only static images are supported. The +rightmost pixel of the image will be stretched to fill the track.
The color used for the track to the left of the button. Overrides the +default blue gradient image.
Sets an image for the thumb. Only static images are supported.
Assigns a single image for the track. Only static images are supported. +The center pixel of the image will be stretched to fill the track.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
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.
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!
Component to control the app status bar.
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.
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.
If the transition between status bar property changes should be animated. +Supported for backgroundColor, barStyle and hidden.
If the status bar is hidden.
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.
Sets the color of the status bar text.
If the network activity indicator should be visible.
The transition effect when showing and hiding the status bar using the hidden
+prop. Defaults to 'fade'.
Show or hide the status bar
| Name and Type | Description |
|---|---|
| hidden boolean | The dialog's title. |
| [animation] | Optional animation when + changing the status bar hidden property. |
Set the status bar style
| Name and Type | Description |
|---|---|
| style | Status bar style to set |
| [animated] boolean | Animate the style change. |
Control the visibility of the network activity indicator
| Name and Type | Description |
|---|---|
| visible boolean | Show the indicator. |
Set the background color for the status bar
| Name and Type | Description |
|---|---|
| color string | Background color. |
| [animated] boolean | Animate the style change. |
Control the translucency of the status bar
| Name and Type | Description |
|---|---|
| translucent boolean | Set as translucent. |
Status bar style
| Value | Description |
|---|---|
| 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 |
Status bar animation
| Value | Description |
|---|---|
| none | No animation |
| fade | Fade animation |
| slide | Slide animation |
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
Use StatusBar for mutating the status bar.
You can edit the content above on GitHub and send us a pull request!
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 like backgroundColor instead of like 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:
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!
A StyleSheet is an abstraction similar to CSS StyleSheets
Create a new StyleSheet:
Use a StyleSheet:
Code quality:
Performance:
Creates a StyleSheet style reference from the given object.
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:
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.
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.
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', + }, + });
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:
Alternative use:
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!
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
If true the user won't be able to toggle the switch. +Default value is false.
Invoked with the new value when the value changes.
Used to locate this view in end-to-end tests.
The value of the switch. If true the switch will be turned on. +Default value is false.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
beginEvent/endEvent for starting and then ending a profile within the same call stack frame
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
counterEvent registers the value to the profileName on the systrace timeline
Relay profiles use await calls, so likely occur out of current stack frame +therefore async variant of profiling is used
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.
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.
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!
Little red bubble that sits at the top right of the icon.
A custom icon for the tab. It is ignored when a system icon is defined.
Callback when this tab is being selected, you should change the state of your +component to set selected={true}.
If set to true it renders the image as original, +it defaults to being displayed as a template
It specifies whether the children are visible or not. If you see a +blank content, you probably forgot to add a selected one.
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.
React style object.
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.
Text that appears under the icon. It is ignored when a system icon +is defined.
You can edit the content above on GitHub and send us a pull request!
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.
A Boolean value that indicates whether the tab bar is translucent
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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, and will automatically post the results to your PR.
We don't have perfect test coverage of course, especially for complex end-to-end interactions with the user, so many changes will still require significant manual verification, but we would love it if you want to help us increase our test coverage and add more tests and test cases!
Jest tests are JS-only tests run on the command line with node. The tests themselves live in the __tests__ directories of the files they test, and there is a large emphasis on aggressively mocking out functionality that is not under test for failure isolation and maximum speed. You can run the existing React Native jest tests with
from the react-native root, and we encourage you to add your own tests for any components you want to contribute to. See getImageSource-test.js for a basic example.
To use Jest for your react-native projects we recommend following the React-Native Tutorial on the Jest website.
React Native uses the Buck build tool to run tests. Unit tests run locally on your machine, no emulator is needed. To run the tests:
React Native uses the Buck build tool to run tests. Integration tests run on an emulator / device and verify that modules and components, as well as the core parts of React Native (such as the bridge) work well end-to-end.
Make sure you have the path to the Android NDK set up, see Prerequisites.
To run the 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 IntegrationTestHarnessTest.js, UIExplorerIntegrationTests.m, and IntegrationTestsApp.js for example usage and integration points.
You can run integration tests locally with cmd+U in the IntegrationTest and UIExplorer apps in Xcode.
A common type of integration test is the snapshot test. These tests render a component, and verify snapshots of the screen against reference images using TestModule.verifySnapshot(), using the FBSnapshotTestCase library behind the scenes. Reference images are recorded by setting recordMode = YES on the RCTTestRunner, then running the tests. Snapshots will differ slightly between 32 and 64 bit, and various OS versions, so it's recommended that you enforce tests are run with the correct configuration. It's also highly recommended that all network data be mocked out, along with other potentially troublesome dependencies. See SimpleSnapshotTest for a basic example.
If you make a change that affects a snapshot test in a PR, such as adding a new example case to one of the examples that is snapshotted, you'll need to re-record the snapshot reference image. To do this, simply change to _runner.recordMode = YES; in UIExplorer/UIExplorerSnapshotTests.m, re-run the failing tests, then flip record back to NO and submit/update your PR and wait to see if the Travis build passes.
You can edit the content above on GitHub and send us a pull request!
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:
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.
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.
numberOfLines must be set in conjunction with this prop.
clipis working only for iOS
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.
Invoked on mount and layout changes with
{nativeEvent: {layout: {x, y, width, height}}}
This function is called on long press.
e.g., `onLongPress={this.increaseSize}>``
This function is called on press.
e.g., `onPress={() => console.log('1st')}``
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.
Specifies text alignment. The value 'justify' is only supported on iOS and
+fallbacks to left on Android.
Used to locate this view in end-to-end tests.
Lets the user select text, to use the native copy and paste functionality.
Specifies whether font should be scaled down automatically to fit given style constraints.
Specifies whether fonts should scale to respect Text Size accessibility setting on iOS. The
+default is true.
Specifies smallest possible scale a font can reach when adjustsFontSizeToFit is enabled. (values 0.01-1.0).
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!
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.
Behind the scenes, React Native converts this to a flat NSAttributedString or SpannableString that contains the following information:
On iOS, you can nest views within your Text component. Here's an example:
In order to use this feature, you must give the view a
widthand aheight.
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.
On the web, the usual way to set a font family and size for the entire document is to write:
When the browser is trying to render a text node, it's going to go all the way up to the root element of the tree and find an element with a font-size attribute. An unexpected property of this system is that any node can have font-size attribute, including a <div>. This was designed for convenience, even though not really semantically correct.
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>.
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.
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:
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.
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!
IOS # | Edit on GitHub |
ANDROID # | Edit on GitHub |
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:
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:
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.
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.If false, disables auto-correct. The default value is true.
If true, focuses the input on componentDidMount.
+The default value is false.
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.
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.
If false, text is not editable. The default value is true.
Determines which keyboard to open, e.g.numeric.
The following values work across platforms:
defaultnumericemail-addressphone-padLimits the maximum number of characters that can be entered. Use this +instead of implementing the logic in JS to avoid flicker.
If true, the text input can be multiple lines.
+The default value is false.
Callback that is called when the text input is blurred.
Callback that is called when the text input's text changes.
Callback that is called when the text input's text changes. +Changed text is passed as an argument to the callback handler.
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.
Callback that is called when text input ends.
Callback that is called when the text input is focused.
Invoked on mount and layout changes with {x, y, width, height}.
Callback that is called when the text input selection is changed.
Callback that is called when the text input's submit button is pressed.
+Invalid if multiline={true} is specified.
The string that will be rendered before text input has been entered.
Determines how the return key should look. On Android you can also use
+returnKeyLabel.
Cross platform
The following values work across platforms:
donegonextsearchsendAndroid Only
The following values work on Android only:
nonepreviousiOS Only
The following values work on iOS only:
defaultemergency-callgooglejoinrouteyahooIf true, the text input obscures the text entered so that sensitive text
+like passwords stay secure. The default value is false.
If true, all text will automatically be selected on focus.
The start and end of the text input's selection. Set start and end to +the same value to position the cursor.
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.
If defined, the provided image resource will be rendered on the left.
Padding between the inline image, if any, and the text input itself.
Sets the number of lines for a TextInput. Use it with multiline set to
+true to be able to fill the lines.
Sets the return key to the label. Use it instead of returnKeyType.
When the clear button should appear on the right side of the text view.
If true, clears the text field automatically when editing begins.
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'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.
Determines the color of the keyboard.
Callback that is called when a key is pressed.
+Pressed key value is passed as an argument to the callback handler.
+Fires before onChange callbacks.
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
DocumentSelectionStatein +vendor/document/selection/DocumentSelectionState.js
You can edit the content above on GitHub and send us a pull request!
IOS # | Edit on GitHub |
ANDROID # | Edit on GitHub |
Opens the standard Android time picker dialog.
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.
A time has been selected.
The dialog has been dismissed.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
Timers are an important part of an application and React Native implements the browser timers.
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.
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:
Compare this to other scheduling alternatives:
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:
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.
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!
This exposes the native ToastAndroid module as a JS module. This has a function 'show' +which takes the following parameters:
There is also a function showWithGravity to specify the layout gravity. May be
+ToastAndroid.TOP, ToastAndroid.BOTTOM, ToastAndroid.CENTER.
Basic usage:
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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:
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 actionicon: 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 nevershowWithText: boolean, whether to show text alongside the icon or notSets 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.
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.
Sets the toolbar logo.
Sets the navigation icon.
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.
Callback called when the icon is selected.
Sets the overflow icon.
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.
Sets the toolbar subtitle.
Used to locate this view in end-to-end tests.
Sets the toolbar title.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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 adding a view to the view hierarchy, which can 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.
Example:
NOTE: TouchableHighlight must have one child (not zero or more than one)
If you wish to have several child components, wrap them in a View.
Determines what the opacity of the wrapped view should be when touch is +active.
Called immediately after the underlay is hidden
Called immediately after the underlay is shown
You can edit the content above on GitHub and send us a pull request!
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:
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.
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.
Creates an object that represents android theme's default background for +selectable elements (?android:attr/selectableItemBackground).
Creates an object that represent android theme's default background for borderless +selectable elements (?android:attr/selectableItemBackgroundBorderless). +Available on android API level 21+.
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+.
| Name and Type | Description |
|---|---|
| color string | The ripple color |
| borderless boolean | If the ripple can render outside it's bounds |
You can edit the content above on GitHub and send us a pull request!
A wrapper for making views respond properly to touches. +On press down, the opacity of the wrapped view is decreased, dimming it. +This is done without actually changing the view hierarchy, and in general is +easy to add to an app without weird side-effects.
Example:
Determines what the opacity of the wrapped view should be when touch is +active. Defaults to 0.2.
Animate the touchable to a new opacity.
You can edit the content above on GitHub and send us a pull request!
Do not use unless you have a very good reason. All the elements that +respond to press should have a visual feedback when touched. This is +one of the primary reason a "web" app doesn't feel "native".
NOTE: TouchableWithoutFeedback supports only one child
If you wish to have several child components, wrap them in a View.
Delay in ms, from onPressIn, before onLongPress is called.
Delay in ms, from the start of the touch, before onPressIn is called.
Delay in ms, from the release of the touch, before onPressOut is called.
If true, disable all interactions for this component.
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.
Invoked on mount and layout changes with
{nativeEvent: {layout: {x, y, width, height}}}
Called when the touch is released, but not if cancelled (e.g. by a scroll +that steals the responder lock).
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!
You can edit the content above on GitHub and send us a pull request!
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.
The React Native packager runs on port 8081. If another process is already using that port (such as McAfee Antivirus on Windows), you can either terminate that process, or change the port that the packager uses.
Run the following command on a Mac to find the id for the process that is listening on port 8081:
$ sudo lsof -n -i4TCP:8081 | grep LISTEN
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.
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.
To change the port used by an iOS application, edit the AppDelegate.m file in the ios folder. Scroll down to the line where the bundle location is defined, and replace 8081 with the new port.
If you encounter an error such as "npm WARN locking Error: EACCES" while using the React Native CLI, try running the following:
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:
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.
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.
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:
If you encounter a ShellCommandUnresponsiveException exception such as:
Try downgrading your Gradle version to 1.2.3 in android/build.gradle.
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:
You can edit the content above on GitHub and send us a pull request!
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.
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:
If you are feeling curious, you can play around with sample code directly in the web simulators. You can also paste it into your index.ios.js or index.android.js file to create a real app on your local machine.
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.
So this code is defining HelloWorldApp, a new Component, and it's registering it with the AppRegistry. When you're building a React Native app, you'll be making new components a lot. Anything you see on the screen is some sort of component. A component can be pretty simple - the only thing that's required is a render function which returns some JSX to render.
The AppRegistry just tells React Native which component is the root one for the whole application. You won't be thinking about AppRegistry a lot - there will probably just be one call to AppRegistry.registerComponent in your whole app. It's included in these examples so you can paste the whole thing into your index.ios.js or index.android.js file and get it running.
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!
Upgrading to new versions of React Native will give you access to more APIs, views, developer tools +and other goodies. Because React Native projects are essentially made up of an Android project, an +iOS project and a JavaScript project, all combined under an npm package, upgrading can be rather +tricky. But we try to make it easy for you. Here's what you need to do to upgrade from an older +version of React Native:
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. For example, to upgrade to the version 0.34, in a terminal run:
The new npm package will likely contain updates to the files that are normally generated when you
+run react-native init, like the iOS and the Android sub-projects. To get these latest changes,
+run this in a terminal:
This will check your files against the latest template and perform the following:
h to get a list of possible commands.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!
The ListView component displays a vertically scrolling list of changing, but similarly structured, data.
ListView works well for long lists of data, where the number of items might change over time. Unlike the more generic ScrollView, the ListView only renders elements that are currently showing on the screen, not all the elements at once.
The ListView component requires two props: dataSource and renderRow. dataSource is the source of information for the list. renderRow takes one item from the source and returns a formatted component to render.
This example creates a simple ListView of hardcoded data. It first initializes the dataSource that will be used to populate the ListView. Each item in the dataSource is then rendered as a Text component. Finally it renders the ListView and all Text components.
A
rowHasChangedfunction is required to useListView. Here we just say a row has changed if the row we are on is not the same as the previous row.
One of the most common uses for a ListView is displaying data that you fetch from a server. To do that, you will need to learn about networking in React Native.
You can edit the content above on GitHub and send us a pull request!
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.
ScrollView works best to present a small amount of things of a limited size. All the elements and views of a ScrollView are rendered, even if they are not currently shown on the screen. If you have a long list of more items that can fit on the screen, you should use a ListView instead. So let's learn about the ListView next.
You can edit the content above on GitHub and send us a pull request!
Mobile apps rarely consist of just one screen. As soon as you add a second screen to your app, you will have to take into consideration how the user will navigate from one screen to the other.
You can use navigators to transition between multiple screens. These transitions can be typical side-to-side animations down a master/detail stack, or vertical modal popups.
React Native has several built-in navigation components, but for your first app you will probably want to use Navigator. It provides a JavaScript implementation of a navigation stack, so it works on both iOS and Android and is easy to customize.

At this point you should feel comfortable rendering all sorts of components in your app, be it a simple View with Text inside, or a ScrollView with a list of Images. Together, these components make up a scene (another word for screen) in your app.
A scene is nothing other than a React component that is typically rendered full screen. This is in contrast to a Text, an Image, or even a custom SpinningBeachball component that is meant to be rendered as part of a screen. You may have already used one without realizing it - the "HelloWorldApp", the "FlexDirectionBasics", and the "ListViewBasics" components covered earlier in the tutorial are all examples of scenes.
For simplicity's sake, let's define a simple scene that displays a bit of text. We will come back to this scene later as we add navigation to our app. Create a new file called "MyScene.js" with the following contents:
Notice the export default in front of the component declaration. This will export the component, and in turn allow other components to import it later on, like so:
We now have a simple app that renders your scene and nothing else. In this case, MyScene is a simple example of a reusable React component.
Enough about scenes, let's start navigating. We will start by rendering a Navigator, and then let the Navigator render the scene for you by passing in your own render function to its renderScene prop.
Something you will encounter a lot when dealing with navigation is the concept of routes. A route is an object that contains information about a scene. It is used to provide all the context that the navigator's renderScene function needs to render a scene. It can have any number of keys to help distinguish your scene, and I happened to pick a single title key for the above example.
In order to transition to a new scene, you will need to learn about push and pop. These two methods are provided by the navigator object that is passed to your renderScene function above. They can be used, as you may have realized, to push and pop routes into your navigation stack.
A more complete example that demonstrates the pushing and popping of routes. Edit your index*.js file to look something like this:
And your MyScene.js to match this:
In this example, the MyScene component is passed the title of the current route via the title prop. It displays two tappable components that call the onForward and onBack functions passed through its props, which in turn will call navigator.push() and navigator.pop() as needed.
Check out the Navigator API reference for more Navigator code samples, or read through the Navigation guide for other examples of what you can do with navigators.
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!
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
@deprecated
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
Views are designed to be used withStyleSheetfor clarity +and performance, although inline styles are also supported.
For View responder props (e.g., onResponderMove), the synthetic touch event passed to them
+are of the following form:
nativeEventchangedTouches - 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.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.
When true, indicates that the view is an accessibility element. By default,
+all the touchable elements are accessible.
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.
When accessible is true, the system will try to invoke this function
+when the user performs accessibility tap gesture.
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.
When accessible is true, the system will invoke this function when the
+user performs the magic tap gesture.
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.
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.
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.
The user is moving their finger.
View.props.onResponderMove: (event) => {}, where event is a synthetic touch event as
+described above.
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.
Fired at the end of the touch.
View.props.onResponderRelease: (event) => {}, where event is a synthetic touch event as
+described above.
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.
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.
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.
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.
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-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:Since
pointerEventsdoes not affect layout/appearance, and we are +already deviating from the spec by adding additional modes, we opt to not +includepointerEventsonstyle. On some platforms, we would need to +implement it as aclassNameanyways. Usingstyleor not is an +implementation detail of the platform.
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).
(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.
Used to locate this view in end-to-end tests.
This disables the 'layout-only view removal' optimization for this view!
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'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.
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.
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.
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.
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.
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.
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!
Examples # | Edit on GitHub |
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:
Index of initial page that should be selected. Use setPage method to
+update the page, and onPageSelected to monitor page changes
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.
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.
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
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
Blank space to show between pages. This is only visible while scrolling, pages are still +edge-to-edge.
When false, the content does not scroll. +The default value is true.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
WebView renders web content in a native view.
You can use this component to navigate back and forth in the web view's +history and configure various properties for the web content.
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.
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}.
DeprecatedUse the source prop instead.
Set this to provide JavaScript that will be injected into the web page +when the view loads.
Boolean that determines whether HTML5 audio and video requires the user
+to tap them before they start playing. The default value is true.
Function that is invoked when the WebView load fails.
Function that is invoked when the WebView has finished loading.
Function that is invoked when the WebView load succeeds or fails.
Function that is invoked when the WebView starts loading.
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.
Function that is invoked when the WebView loading starts or ends.
Function that returns a view to show if there's an error.
Function that returns a loading indicator.
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.
Loads static html or a uri (with optional headers) in the WebView.
Boolean value that forces the WebView to show the loading view
+on the first load.
The style to apply to the WebView.
DeprecatedUse the source prop instead.
Boolean value to control whether DOM Storage is enabled. Used only in +Android.
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.
Sets the user-agent for the WebView.
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.
Boolean value that determines whether the web view bounces
+when it reaches the edge of the content. The default value is true.
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'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:
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.
Boolean value that determines whether scrolling is enabled in the
+WebView. The default value is true.
You can edit the content above on GitHub and send us a pull request!
Examples # | Edit on GitHub |
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.
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.
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.

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.
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!
Some of these are hybrid native/React Native apps.