nick / react-native-carousel

Carousel component for react-native
MIT License
458 stars 107 forks source link

Multiple Child Components #13

Closed albertwchang closed 9 years ago

albertwchang commented 9 years ago

By any chance, does anyone know how to dynamically produce a set of components for the Carousel? For example, if I have an array of numbers and want to dynamically create the View components for them, how would that be done?

I'm not getting any love using "_.each"...

Example Code:

render: function() {
   return (
    <Carousel style={imgStyle}>
           { _.each([1, 2, 3, 4], function(num) {
              <View><Text>{num}</Text></View>
       })}
    </Carousel>
   );
}
nick commented 9 years ago

try adding a return statement before <View><Text>{num}</Text></View>

alinz commented 9 years ago

I think waht @nick says it's correct. You can also use es6 auto return feature as well, if you are lazy to type as I am :P.

render: function() {
   return (
    <Carousel style={imgStyle}>
       {
         _.each([1, 2, 3, 4], (num) => <View><Text>{num}</Text></View> ) 
       }
    </Carousel>
   );
}
albertwchang commented 9 years ago

Totally worked you guys. Thanks @alinz && @nick

AndrewTHuang commented 8 years ago

I'm coming across a related issue. When I map over a collection of <Image /> components to be rendered in Carousel, each one is assigned an indicator as expected. However, if I add another element to Carousel outside of the mapped collection, then Carousel treats the mapped collection as just one element, and only two indicators are rendered.

Example

const URIs = ['uri1', 'uri2', 'uri3'];

const imageCollection = (
  URIs.map(myURI =>
    <Image
      source={{uri: myURI}}
    />
  )
);

<Carousel>
  {imageCollection}
</Carousel>

// This works as expected! Three indicators for three <Image /> components
const URIs = ['uri1', 'uri2', 'uri3'];

const imageCollection = (
  URIs.map(myURI =>
    <Image
      source={{uri: myURI}}
    />
  )
);

<Carousel>
  {imageCollection}
  <Image
    source={uri: 'uri4'}
  />
</Carousel>

// In this case, only two indicators are rendered for four <Image /> components

Has anyone come across this scenario? Thoughts?

nick commented 8 years ago

How about:

const URIs = ['uri1', 'uri2', 'uri3'];

let imageCollection = (
  URIs.map(myURI =>
    <Image
      source={{uri: myURI}}
    />
  )
);
imageCollection.push(
  <Image
    source={uri: 'uri4'}
  />
);

<Carousel>
  {imageCollection}
</Carousel>
AndrewTHuang commented 8 years ago

Yeah that works, but could get messy when dealing with a more complex example. I'll submit a PR if I can find a reliable solution, thanks!