Recibo una cantidad desconocida de datos (imágenes) de un extremo de la API y quiero usar flexbox para mostrar las imágenes en 2 filas y una cantidad desconocida de columnas según la cantidad de datos. ¿Cómo se hace?
const [artistes, setArtiste] = useState(null); //get request to endpoint fetch('http://localhost:8000/museb/artist/',{ method: 'GET', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }}) .then(response => response.json()) .then(jsonResponse => setArtiste(jsonResponse) ) .catch(error => console.log(error)) .finally(setLoading(false)); }, [])Aquí es donde estoy renderizando los datos.
<View style={{flexDirection: "row"}}> {artistes.map((artiste, index) => ( <TouchableOpacity key={index} onPress={() => navigation.navigate("Musicplayer")} style={styles.musiccontentsmall}> <Image source={{uri: "http://localhost:8000"+artiste.image}} style={styles.smallimage}/> </TouchableOpacity>))} </View> )}"flexDireciton: fila" pondrá todo el contenido en una sola fila, pero quiero que esté en dos filas
Aquí tienes dos opciones.
El primero es responder a su pregunta específica usando solo flexbox: el truco aquí es usar el estilo de ajuste, combinando el tamaño del ancho, por lo que con el 50% usamos dos columnas o el 33% usamos tres.
<View style={{flexDirection: "row", flexWrap: "wrap"}}> {artistes.map((artiste, index) => ( <TouchableOpacity key={index} onPress={() => navigation.navigate("Musicplayer")} style={[styles.musiccontentsma, { width:"50%" }]}> <Image source={{uri: "http://localhost:8000"+artiste.image}} style={styles.smallimag}/> </TouchableOpacity> ))} </View>La segunda opción y la mejor en términos de rendimiento (porque estás usando imágenes):
<FlatList data={artistes} numColumns={2} renderItem={({ item }) => this._renderItem(item)} keyExtractor={(item, index) => index.toString()} /> _renderItem = item => { return ( <View styles={{ flex: 0.5 }}> {...} </View> ) }