I cannot render elements dynamically using foreach

Asked

Viewed 119 times

-1

I wonder if you have how to render the component Drawer.Screen inside Drawer.Navigator, dynamically. I tried to put the components in an array (materias/index.js) and traverse them with .forEach(), as shown in Routes/index.js. However, clicking on any of the pages generates the following error:

"The action 'NAVIGATE' with payload {"name":"Matematica"} was not handled by any navigator."

I mean, it didn’t render.

Materials/index.js:

import Matematica from '~/pages/materias/Matematica';
import Portugues from '~/pages/materias/Portugues';
import Fisica from '~/pages/materias/Fisica';

export default function Materias() {
  return [
    { name: 'Matematica', component: Matematica },
    { name: 'Portugues', component: Portugues },
    { name: 'Fisica', component: Fisica },
  ];
}

Routes/index.js:

import React from 'react';
import { createDrawerNavigator } from '@react-navigation/drawer';
import HomePage from '~/pages/HomePage';
import Materias from '~/pages/materias'

const Drawer = createDrawerNavigator();

function DrawerNavigation({ navigation }) { 

    const materias = Materias();

    return (
        <Drawer.Navigator
          initialRouteName="HomePage"
          drawerContent={() => ...}
        >
        
        <Drawer.Screen
          name="HomePage"
          component={HomePage}
          options={...}
        />
        
        {/* Lugar que gera o erro */}
        {materias.forEach((element) => (
          <Drawer.Screen
            name={element.name}
            component={element.component}
            options={...}
          />
        ))}

        </Drawer.Navigator>
    )
}

1 answer

1


.forEach() vs .map()

When you want to display some kind of list on a component in React, use the Array.map(), because in addition to the desired function to be executed, a result is returned for each element of the Array. The Array.forEach() only executes the function and does not return a value.

const arr = ['a', 'b', 'c'];

console.log('Retorno do .forEach():',  arr.forEach(el => el));
console.log('Retorno do .map():',  arr.map(el => el));

Rendering lists in React

Being even more specific, the components returned within the .map() must possess a key. See in the documentation Lists and Keys.

Keys help React identify which items have been changed, added, or removed. Keys must be assigned to the elements within the array to give a stable identity to the elements.

The code could go like this:

{materias.forEach((element) => (
  <Drawer.Screen
    key={element.name} {/* Identificador */}
    name={element.name}
    component={element.component}
    options={...}
  />
))}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.