@@ -89,6 +89,7 @@ export default class Carousel extends BaseComponent {
8989 : props . pageWidth + props . itemSpacings || Constants . screenWidth ;
9090
9191 this . state = {
92+ containerWidth : undefined ,
9293 currentPage : this . shouldUsePageWidth ( ) ? this . getCalcIndex ( props . initialPage ) : props . initialPage ,
9394 currentStandingPage : props . initialPage ,
9495 pageWidth : defaultPageWidth ,
@@ -145,11 +146,31 @@ export default class Carousel extends BaseComponent {
145146 return index ;
146147 }
147148
149+ getSnapToOffsets = ( ) => {
150+ const { itemSpacings} = this . props ;
151+ const { containerWidth, pageWidth} = this . state ;
152+
153+ if ( containerWidth ) {
154+ const spacings = pageWidth === containerWidth ? 0 : itemSpacings ;
155+ const initialBreak = pageWidth - ( containerWidth - pageWidth - spacings ) / 2 ;
156+ const snapToOffsets = _ . times ( presenter . getChildrenLength ( this . props ) , index => initialBreak + index * pageWidth ) ;
157+ return snapToOffsets ;
158+ }
159+ }
160+
148161 shouldUsePageWidth ( ) {
149162 const { loop, pageWidth} = this . props ;
150163 return ! loop && pageWidth ;
151164 }
152165
166+ onContainerLayout = ( { nativeEvent : { layout : { width : containerWidth } } } ) => {
167+ const update = { containerWidth} ;
168+ if ( ! this . props . pageWidth ) {
169+ update . pageWidth = containerWidth ;
170+ }
171+ this . setState ( update ) ;
172+ }
173+
153174 onContentSizeChange = ( ) => {
154175 // this is to handle initial scroll position (content offset)
155176 if ( Constants . isAndroid ) {
@@ -200,6 +221,11 @@ export default class Carousel extends BaseComponent {
200221 } ;
201222
202223 renderChildren ( ) {
224+ const { containerWidth} = this . state ;
225+ if ( ! containerWidth && ! this . shouldUsePageWidth ( ) ) {
226+ return null ;
227+ }
228+
203229 const { children, loop} = this . props ;
204230 const length = presenter . getChildrenLength ( this . props ) ;
205231
@@ -257,15 +283,13 @@ export default class Carousel extends BaseComponent {
257283
258284 render ( ) {
259285 const { containerStyle, itemSpacings, ...others } = this . props ;
260- const { initialOffset, pageWidth } = this . state ;
286+ const { initialOffset} = this . state ;
261287
262288 const scrollContainerStyle = this . shouldUsePageWidth ( ) ? { paddingRight : itemSpacings } : undefined ;
263- const spacings = pageWidth === Constants . screenWidth ? 0 : itemSpacings ;
264- const initialBreak = pageWidth - ( Constants . screenWidth - pageWidth - spacings ) / 2 ;
265- const snapToOffsets = _ . times ( presenter . getChildrenLength ( this . props ) , index => initialBreak + index * pageWidth ) ;
289+ const snapToOffsets = this . getSnapToOffsets ( ) ;
266290
267291 return (
268- < View style = { containerStyle } >
292+ < View style = { containerStyle } onLayout = { this . onContainerLayout } >
269293 < ScrollView
270294 { ...others }
271295 ref = { this . carousel }
0 commit comments