Step-by-step guide on dynamically generating table rows in React

I have been trying to dynamically create a table with rows and columns based on an array. While my rest request is functioning properly, I am facing challenges when attempting to switch from a hard-coded example to a dynamic approach using loops or mapping.

return {
    columns: [
      { Header: "Member", accessor: "name", width: "45%", align: "left" },
      { Header: "Role", accessor: "function2", align: "left" },
      { Header: "Status", accessor: "status", align: "center" },
      { Header: "Since", accessor: "employed", align: "center" },
      { Header: "action", accessor: "action", align: "center" },
    ],

    rows: [
      {
        name: <User image={team2} name={users[0].firstName} email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7cac6cecbe7cac289c4c8ca">[email protected]</a>" />,
      },
      {
        name: <User image={team2} name={users[1].firstName} email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="583539313418353d763b3735">[email protected]</a>" />,
      },
    ],
  };
}

Despite trying to implement a loop, I am still unable to get it working as intended.

 return {
    columns: [
      { Header: "Member", accessor: "name", width: "45%", align: "left" },
      { Header: "Role", accessor: "function2", align: "left" },
      { Header: "Status", accessor: "status", align: "center" },
      { Header: "Since", accessor: "employed", align: "center" },
      { Header: "action", accessor: "action", align: "center" },
    ],
    rows:  users.map((user) => ({
        name: <User image={team2} name={user.firstName} email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b767a72775b767e35787476">[email protected]</a>!" />
    })
  };

When attempting the suggested change using map, I receive an error stating "Unexpected token, expected ","."

Answer №1

Do not include strings in the rows array

let rows=[]

users.map((user)=>{
    rows.push({
        name: <User image={team2} name={user.firstName} email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b4b8b0b599b4bcf7bab6b4">[email protected]</a>! />
    })
})

Answer №2

Your result may not be as expected because forEach does not have a return value, and you may not be utilizing the data within your loop effectively.

To achieve the desired outcome, consider using map which will generate an array as shown below:

{
  rows: users.map((user) => ({
    name: <User image={team2} name={user.firstName} email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="395458505579545c175a56cd45495454">[email protected]</a>!" />
  }))
}

With map function, an array is automatically returned, eliminating the need for manual array management.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieve the current image source URL using JavaScript

In the template below, I am looking to extract the current img src URL and utilize it in a fancybox button. For example, in the template provided, there are 3 images from https://farm6.staticflickr.com. When clicking on these images, the fancybox will ope ...

The "require" keyword cannot be used in a Node-RED Function node

When working with a Node-RED Function Node, the first line I include is: var moment = require('moment-timezone'); I'm attempting to create a timezone accurate date/time stamp for sensor data. However, when this node runs, I encounter the fo ...

Verify if the form has been successfully validated

Here is a simple form using Tag Helper: <form asp-area="Admin" asp-controller="Categories" asp-action="EditCategory" method="post" id="CategoryForm"> <div class="row"> ...

Yii employs the use of quickdlgs to efficiently generate fresh entries within the CGrid view

Within my web application, I am attempting to implement an iframe button using quickdlgs to create new records. However, upon clicking the iframe button, instead of being directed to the 'create' webpage, I am presented with an empty iframe. Here ...

Getting a 406 (Not acceptable) error when trying to perform an AJAX action in Rails 4

I am attempting to automatically refresh a specific partial view every 60 seconds on the homepage. To make it easier to manage, I have divided the actions into two routes. However, I am encountering an issue with the respond_to block and could use some ass ...

I can't seem to locate the datepicker in Material UI Next. Can you point

I'm attempting to use the next branch of Material UI from https://github.com/callemall/material-ui/tree/next. I need to utilize the layout component, but it seems that the DatePicker component is missing. How can I include the DatePicker in the next b ...

Guide to utilizing an if statement to return a string as the title in a Tooltip pro

When attempting to dynamically set the title of a tooltip based on a function and using an if statement, I encountered an error. const getStatusMessage = (answer: AnswerStatus) => { if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus ...

The latest update of NextJS, version 13.1.4, encounters issues when implementing SCSS support with the error message "Module next/dist/compiled/sass-loader/fibers.js not

After setting up a new NextJS project, I decided to incorporate SCSS support. The guidelines provided in the documentation seemed straightforward. Following the installation instructions and including an import of SCSS as shown below: import "@/styles ...

Obtain an array of documents within collections using Firestore in React.js

I am encountering issues with the code below as I am trying to retrieve a single document based on the ID provided. import React, {useState, useEffect } from 'react'; import { useParams } from 'react-router-dom'; import {db} from &q ...

Calculating tables dynamically with jQuery

I have encountered an issue with my dynamic form/table where newly added rows are not being calculated correctly. While the static elements function as expected, the IDs and classes of the new rows do not align with the calculation logic. Can someone offe ...

Ways to exhibit API information leveraging the prowess of Ajax

I am looking for a way to utilize the API in order to present data in an organized manner, similar to the following example: Job Title: Agricultural and Related Trades Percentage of Occupancies in Area: 15.41% Unfortunately, my attempt to showcase the d ...

jQuery triggers change event twice when radio group is manually modified

After selecting "A&L" in the dropdown menu, the radio group is hidden and its value is changed to "n". I attempted to trigger the change event to make the "Hello" message disappear as well, but it seems to be executing twice - once correctly and then ...

There is a route available, however, the result returned is 404

I'm having some trouble sending a username and password to the backend. After making the request, I received a 404 error related to the route. Backend - index.js const express = require("express"); const app = express(); const port = 3001; ...

What could be preventing my map function from successfully displaying API data on the browser?

Having trouble finding the correct path to map over nested data in my console. I need an Image component for each product in the array. https://i.stack.imgur.com/3nSj1.png Attempting to map over the object shown in the image below. Here is the async functi ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

Generate a fresh array using a current array comprising of objects

Greetings! I am facing a challenge with an array of objects like the one shown below: const data = [ {day: "Monday", to: "12.00", from: "15.00"}, {day: "Monday", to: "18.00", from: "22.00"}, {day: ...

Unable to alter the pagination's selected page color to grey with material UI pagination components

Currently, I am implementing pagination using material UI. While I have successfully changed the page color to white, I am facing difficulty in changing the selected page color to grey. This issue arises because the background color is dark. import React, ...

AngularFire and Ionic - There is no data being sent to the server from the form

I am using Ionic and AngularFire to build my app, but I have encountered a new issue: the form data is empty! Only the fields in my Firebase database are visible. How can I retrieve the user-entered form data from the Firebase database? Here is a screensh ...

Attempting to extract a parameter from a URL and pass it as an argument to a function for the purpose of locating objects based on

I am trying to retrieve data from a URL http://localhost:3000/share/user=sampleuser to display objects with an author value that matches the one in the URL. However, I encountered an error when attempting to call a function that extracts the value from t ...

Verify if there is a value in at least one of the multiple input fields

I have 4 input fields and I need to check if at least one of them has a value. If none of them are filled out, I want the function to stop. Below is the current code snippet I'm using but it's not working as expected because it doesn't ente ...