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.

Generate a View using a loop with React Native. Example: Dynamic Menu.

Tiempo de lectura: 2 minutos

Translated content in English:

The first thing we have to do is create the component (if you don’t know what a component is, I recommend this post Create a component in React Native) that will represent our menu. In this case, I call it 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';
//Button Component
const Menu = (props) => {
//Constructor parameters passed through props
const { elementosTab } = props;
//Use map to return elements
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'; //Button Component const Menu = (props) => { //Constructor parameters passed through props const { elementosTab } = props; //Use map to return elements 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';

//Button Component
const Menu = (props) => {

    //Constructor parameters passed through props
    const { elementosTab } = props;

    //Use map to return elements
    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
    }
});

In order to make this code work, you need to install the react-native-paper dependency (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

Now I will explain the code.

First, an object or array containing the attributes representing the view is passed as a property parameter.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//Button Component
const Menu = (props) => {//Constructor parameters passed through props
const { elementosTab } = props;
//Button Component const Menu = (props) => {//Constructor parameters passed through props const { elementosTab } = props;
//Button Component
const Menu = (props) => {//Constructor parameters passed through props

const { elementosTab } = props;

Then, the passed list is traversed using map, and in each iteration, a “row” or element created from the list is returned.

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 represents the element inside the array and is iterated over as if it were a for each loop.

The index attribute represents the current index while iterating over the element.

Now, to build our dynamic element menu, we need to go to our App.js or screen where we want to call the element and construct the list that we will pass as a property.

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";
//Import the component
import Menu from "Menu";
const App = () => {
var elementosTab = [
{
texto: 'Videos',
onPress: alert("Videos"),
},
{
texto: 'Foro',
onPress: alert("Foro"),
},
{
texto: 'Quiz',
onPress: alert("Quiz"),
}
];
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"; //Import the component import Menu from "Menu"; const App = () => { var elementosTab = [ { texto: 'Videos', onPress: alert("Videos"), }, { texto: 'Foro', onPress: alert("Foro"), }, { texto: 'Quiz', onPress: alert("Quiz"), } ]; 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";

//Import the component
import Menu from "Menu";

const App = () => {

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

    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',
    }
});

Now I will explain the relevant part of the code.

First, we import our component (indicating the correct path where we have saved it):

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";

Then, we create the list of objects that will be used to create our menu:

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"),
        }
    ];

Each element will represent a menu tab.
That’s it! Now we can create elements dynamically using React Native.
(Please note that the “Reading Time” part should not be included in the translation. The translation is returned directly in HTML format.)

0

Leave a Comment