Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Generar una vista (View) usando un bucle con React Native. Ejemplo menú dinámico.

Tiempo de lectura: 2 minutos

Podemos crear una lista de elementos y asignarlos a la vista para que devuelva por ejemplo un menú con X pestañas. De esta manera podemos crear un render que tenga una lista y se recorra con un map para devolver cada uno de sus elementos.

Lo primero que tenemos que hacer es crear el componente (si no sabes lo qué es un componente te recomiendo este post Crear un componente en React Native) que va a representar nuestro menú. En este caso lo llamo menu.js

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React from "react";
import { StyleSheet, View } from "react-native";
import { Button } from 'react-native-paper';
//Componente boton
const Menu= (props) => {
//Parametros de constructor se pasan por props
const { elementosTab } = props;
//For para devolver elementos
return (
<View style={styles.container}>
{
elementosTab.map((elemento, index) => {
return (
<Button key={index} style={[styles.boton]} mode="text" onPress={elemento.onPress} >{elemento.texto}</Button>
);
}
)
}
</View>
)
};
export default Menu;
const styles = StyleSheet.create({
boton: {
marginLeft: 5,
marginRight: 5
},
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginTop: 10,
marginBottom: 10,
marginLeft: 10,
marginRight: 10
}
});
import React from "react"; import { StyleSheet, View } from "react-native"; import { Button } from 'react-native-paper'; //Componente boton const Menu= (props) => { //Parametros de constructor se pasan por props const { elementosTab } = props; //For para devolver elementos return ( <View style={styles.container}> { elementosTab.map((elemento, index) => { return ( <Button key={index} style={[styles.boton]} mode="text" onPress={elemento.onPress} >{elemento.texto}</Button> ); } ) } </View> ) }; export default Menu; const styles = StyleSheet.create({ boton: { marginLeft: 5, marginRight: 5 }, container: { flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 10, marginBottom: 10, marginLeft: 10, marginRight: 10 } });
import React from "react";
import { StyleSheet, View } from "react-native";
import { Button } from 'react-native-paper';

//Componente boton
const Menu= (props) => {

    //Parametros de constructor se pasan por props
    const { elementosTab } = props;

    //For para devolver elementos
    return (
        <View style={styles.container}>

            {
                elementosTab.map((elemento, index) => {
                    return (
                        <Button key={index} style={[styles.boton]} mode="text" onPress={elemento.onPress} >{elemento.texto}</Button>
                    );
                }
                )
            }

        </View>
    )
};

export default Menu;

const styles = StyleSheet.create({
    boton: {
        marginLeft: 5,
        marginRight: 5
    },
    container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginTop: 10,
        marginBottom: 10,
        marginLeft: 10,
        marginRight: 10
    }
});

Para poder hacer funcionar este código necesitas instalar la dependencia de react-native-paper (https://callstack.github.io/react-native-paper/)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install react-native-paper
npm install react-native-paper
npm install react-native-paper

Ahora voy a explicar el código.

Primero se pasa por parámetro de propiedad un objeto o array que contiene los atributos que representan la vista.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//Componente boton
const Menu= (props) => {//Parametros de constructor se pasan por props
const { elementosTab } = props;
//Componente boton const Menu= (props) => {//Parametros de constructor se pasan por props const { elementosTab } = props;
//Componente boton
const Menu= (props) => {//Parametros de constructor se pasan por props

const { elementosTab } = props;

Después se recorre la lista que se ha pasado creando un map y devolviendo en cada iteración un «row» o elemento creado mediante la lista.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
elementosTab.map((elemento, index) => {
return (
<Button key={index} style={[styles.boton]} mode="text" onPress={elemento.onPress} >{elemento.texto}</Button>
);
}
)
}
{ elementosTab.map((elemento, index) => { return ( <Button key={index} style={[styles.boton]} mode="text" onPress={elemento.onPress} >{elemento.texto}</Button> ); } ) }
{
                elementosTab.map((elemento, index) => {
                    return (
                        <Button key={index} style={[styles.boton]} mode="text" onPress={elemento.onPress} >{elemento.texto}</Button>
                    );
                }
                )
            }

Elemento, representa el elemento del interior del array y se va recorriendo como si se tratase de un for each.

El atributo index, representa el índice actual al recorrer el elemento.

Ahora, para poder construir nuestro menú de elementos dinámico, tenemos que ir a nuestro App.js o screen dónde queramos llamar al elemento y construir la lista que vamos a pasar por propiedad.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React, { useState } from "react";
import { View, StyleSheet} from "react-native";
//Importamos el componente
import Menu from "Menu";
const App= () => {
var elementosTab = [
{
texto: 'Videos',
onPress: alert("Videos"),
},
{
texto: 'Foro',
onPress: alert("Foro"),
},
{
texto: 'Quiz',
onPress: alert("Quiz"),
}
];
//listaCursos();
return (
<View style={styles.contenedorInicio}>
<View style={[styles.contenedorMenu]}>
<Menu elementosTab={elementosTab} />
</View>
</View>
)
};
export default App;
const styles = StyleSheet.create({
contenedorMenu: {
flex: 1,
height: '50%',
width: '100%',
},
contenedorInicio: {
flex: 1,
alignContent: 'center',
alignItems: 'center',
}
});
import React, { useState } from "react"; import { View, StyleSheet} from "react-native"; //Importamos el componente import Menu from "Menu"; const App= () => { var elementosTab = [ { texto: 'Videos', onPress: alert("Videos"), }, { texto: 'Foro', onPress: alert("Foro"), }, { texto: 'Quiz', onPress: alert("Quiz"), } ]; //listaCursos(); return ( <View style={styles.contenedorInicio}> <View style={[styles.contenedorMenu]}> <Menu elementosTab={elementosTab} /> </View> </View> ) }; export default App; const styles = StyleSheet.create({ contenedorMenu: { flex: 1, height: '50%', width: '100%', }, contenedorInicio: { flex: 1, alignContent: 'center', alignItems: 'center', } });
import React, { useState } from "react";
import { View, StyleSheet} from "react-native";

//Importamos el componente

import Menu from "Menu";

const App= () => {

    var elementosTab = [
        {
            texto: 'Videos',
            onPress: alert("Videos"),
        },
        {
            texto: 'Foro',
            onPress: alert("Foro"),
        },
        {
            texto: 'Quiz',
            onPress: alert("Quiz"),
        }
    ];

    //listaCursos();
    return (
        <View style={styles.contenedorInicio}>
            <View style={[styles.contenedorMenu]}>
                <Menu elementosTab={elementosTab} />
            </View>
        </View>
    )
};

export default App;

const styles = StyleSheet.create({
    contenedorMenu: {
        flex: 1,
        height: '50%',
        width: '100%',
    },
    contenedorInicio: {
        flex: 1,
        alignContent: 'center',
        alignItems: 'center',
    }
});

Ahora voy a explicar la parte relevante del código.

Primero importamos nuestro componente (indicando la ruta correcta dónde lo hemos guardado):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import Menu from "Menu";
import Menu from "Menu";
import Menu from "Menu";

Después creamos la lista de objetos qué nos va a servir para crear nuestro menú:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var elementosTab = [
{
texto: 'Videos',
onPress: alert("Videos"),
},
{
texto: 'Foro',
onPress: alert("Foro"),
},
{
texto: 'Quiz',
onPress: alert("Quiz"),
}
];
var elementosTab = [ { texto: 'Videos', onPress: alert("Videos"), }, { texto: 'Foro', onPress: alert("Foro"), }, { texto: 'Quiz', onPress: alert("Quiz"), } ];
var elementosTab = [
        {
            texto: 'Videos',
            onPress: alert("Videos"),
        },
        {
            texto: 'Foro',
            onPress: alert("Foro"),
        },
        {
            texto: 'Quiz',
            onPress: alert("Quiz"),
        }
    ];

Cada elemento va a representar un tab del menú.

Y finalmente llamamos al componente y pasamos el array como parámetro.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<Menu elementosTab={elementosTab} />
<Menu elementosTab={elementosTab} />
<Menu elementosTab={elementosTab} />

Y listo, ya podemos crear elementos de forma dinámica utilizando React Native.

0

Deja un comentario