`How can an array be passed as props and then rendered in React components?`

I am currently working on creating information cards using React, where I pass the data through props to a base component.

export default function Home() {
    return (
    <Box className={styles.container}>
            <div className={styles.helpCards}>
                <CardBase title={WhatICanDo.title} list={WhatICanDo.links}/>
                <CardBase title={LearnToTalkToMe.title} />
                <CardBase title={QuickLinks.title} list={QuickLinks.links}/>
            </div>
    </Box>

In a separate file, I have stored all the necessary information for these cards. Each card has a title and a list of helpful links associated with it.

export const WhatICanDo = {
    title: 'O que eu posso fazer?',
    links: [
        'Reset de Senha',
        'Dúvidas Frequentes'
    ]
}

export const LearnToTalkToMe = {
    title: 'Aprenda a falar comigo'
}

export const QuickLinks = {
    title: 'Links Rápidos',
    links: [
        'Reset de Senha',
        'Consulta de Ponto',
        'Criação de Chamados',
        'Consulta de Chamados',
        'Dúvidas Frequentes'
    ]
}

Within the file that handles this information and constructs the base of the cards, I need to map over the received list of links so that they are displayed as individual items inside an (< li >) element.

export default function CardBase({ list, title }) {
    const cardsList = [list];

    function cardsMap() {
        return (
            <>
                {cardsList.map((card, index) => 
                    <li key={index}>{card}</li>
                )}
            </> 
        )
    }

    return (
        <Card className=''>
            <CardContent>
                <Typography className='' color='' gutterBottom>
                    {title}
                </Typography>
                
                <Typography className='' variant='' component=''>
                    {cardsMap()}
                </Typography>
            </CardContent>
        </Card>
    );
}

Although everything seems to be set up correctly, I am facing an issue during rendering where all the items in the list are being displayed next to each other instead of vertically stacked as I intended.

Image

Any suggestions on how I can address this problem?

Answer №1

When you use this code snippet

const cardsList = [list]

You are essentially creating a new array that contains the elements of the original array, resulting in a nested data structure like this:

[ // first array
 [ // second array
   'Reset de Senha',
   'Consulta de Ponto',
   'Criação de Chamados',
   'Consulta de Chamados',
   'Dúvidas Frequentes'
  ]
]

The cardsList.map function then iterates over the first array (which only has one element - the second array). To iterate over the links without redeclaring cardsList, simply use list.map.

UPDATE:

If you encounter an error stating that list does not have access to .map, it may be because you did not pass it as a prop in your second CardBase component. Making it optional with

list?.map((card, index) => ...))
should resolve the error (by adding a question mark after list to make it optional).

Answer №2

list represents an array, simply utilize :

const cardList = list; // avoid using [list]

Answer №3

** Feel free to use this snippet

const CardComponent = ({ items, header }) => {

    const cardItems = items; //avoid putting [items] since it's already an array

    function renderCards() {
        return (
            <>
                {cardItems.length && cardItems.map((item, index) =>
                    <li key={index}>{item}</li>
                )}
            </>
        )
    }

    return (
        <Card className=''>
            <CardContent>
                <Typography className='' color='' gutterBottom>
                    {header}
                </Typography>

                <Typography className='' variant='' component=''>
                    {renderCards()}
                </Typography>
            </CardContent>
        </Card>
    );
}

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

reset input fields upon unchecking a checkbox with javascript

Currently in the process of building a form that includes physical address fields and postal address fields. If the user fills in the physical address and the postal address is the same, they can check a box to copy the information over. I have successfull ...

Running Nextjs on Hostinger servers

Currently, I am trying to host my Next.js website on Hostinger. To achieve this, I have exported Next.js as static files in the 'out' directory using the output: 'export' configuration in the next config. After uploading the static fil ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...

The HTTPS protocol seems to be causing CORS issues, but I can access http://localhost without

In my current project using TypeScript with Express, I encountered an issue with implementing CORS. In the past, I have successfully added CORS to regular Express.js projects without TypeScript and assumed it would work similarly. However, when making a ba ...

Create a standalone 404 page using React Router that is completely isolated from any other components

Currently, I am collaborating with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfadbabebcabbaadf2adb0aaabbaadf2bbb0b29fe9f1ebf1ed">[email protected]</a> and the code I am working on looks like this: index.tsx ...

Select component with nested checkboxes for multilevel dropdown

I am interested in developing nested dropdowns with checkboxes, similar to the example shown in this image: Image 1 Is there a way to achieve this functionality using React? I have not been able to find any specific library that allows for this implement ...

Learn how to implement icons within Textfield components using Material-UI and TypeScript in React

I have successfully created a form with validation using TypeScript Material UI and Formik. Now, I am looking to enhance the visual appeal by adding a material UI Icon within the textfield area. Below is a snippet of my code: import React from 'reac ...

The Homescreen.js file is not showing up as expected on the localhost/home page and is not displaying

Struggling to showcase the rooms on my hotel reservation website. Can't seem to crack it. Need some assistance, please. Spent a good 3 hours trying to figure this out. Snippet from My Homescreen.js import React ,{useState, useEffect, } from &apo ...

Graphical Interface for an HTTPAPI

After successfully building a REST API in Node.js using Express that includes queue functionalities, my next goal is to develop a web interface for this API. As a newcomer to JavaScript and Node.js, I would greatly appreciate any advice or guidance on ho ...

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

The Body and HTML elements compress to sizes significantly smaller than the viewport

I am currently working on making my WordPress website responsive. On one of the pages, I have two images that I want to set a max-width of 100% to ensure they are responsive. However, when I shrink the page in Chrome dev tools, I noticed that the <html& ...

Issues with rendering components using ReactJS are causing problems with <p/> and <br/> tags not functioning as expected

I am having trouble using <p/> or <br/> tags to create new lines after a custom ReactJS component that includes Bootstrap CSS with <div className="col-sm-10">. var MyChatClientView = React.createClass({ render: function() { retur ...

NodeJS rendering method for HTML pages

We are in the process of developing a fully functional social networking website that will resemble popular platforms like Facebook or Instagram. Our plan is to utilize Node.js on the server side and we are currently exploring the best technology for rende ...

The use of the picture element, with its ability to support various image formats and sizes, must always include

Recently, I came across a VueJS template that closely resembles HTML but has the following structure: <picture> <source type="image/avif" :scrset="avif" /> <source type="image/webp" :scrset="webp" ...

Steps for assigning innerHTML values to elements within a cloned div

Currently, I am setting up a search form and I require dynamically created divs to display the search results. The approach I am taking involves: Creating the necessary HTML elements. Cloning the structure for each result and updating the content of ...

How to open a new window in a separate desktop on macOS using Javascript

I am currently browsing my website on a Mac computer. I am interested in opening a new tab on the second desktop using Mission Control. Is this achievable? If so, could you please guide me on how to do it? After searching extensively online, I have been u ...

Node.js Native Driver failing to insert data into MongoDb

I've been working on saving data into MongoDb, following a previous example that worked perfectly. However, when I tried to implement a similar approach in my own test app, it failed. Despite not receiving any errors from MongoDb and even getting the ...

What is the best way to manage responsive Bootstrap 3 tables that contain a lot of content?

Currently, I am working on a Wordpress plugin that features a Bootstrap 3 responsive table. However, the challenge lies in the fact that the content within the table data cells is more than just a few words. This specific table consists of three columns: ...

Is there a way to use JavaScript to modify the position of a div element

Can we adjust the div position using CSS (absolute or relative) with JavaScript? Here's an example code snippet: <div id="podpis" style="margin-top: 2rem;"> <div class="invoice-signature"> <span><?=$xml->sanitiz ...

What is the best way to retrieve CoinEx API using access ID and secret key in JavaScript?

Having trouble fetching account information using the CoinEx API and encountering an error. For more information on the API, please visit: API Invocation Description Acquire Market Statistics Inquire Account Info Note : This account is only for test p ...