Exploring Object Attributes in React

I'm working on a React app where I have an array of objects in a file called users.js, and another file named contacts.jsx. In the contacts.jsx file, I am trying to display a Material UI card and access the properties of the object within that card.

Despite using the dot (.) operator, I keep getting 'undefined' in the console.log. Can someone please point out what mistake I might be making and suggest how I can properly access properties like avatar, email, first_name, etc.?

users.js

const users = [{
    id: 1,
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="086f6d677a6f6d266a647d7c60487a6d797a6d7b266166">[email protected]</a>",
    first_name: "George",
    last_name: "Bluth",
    avatar: "https://reqres.in/img/faces/1-image.jpg"
},
    {
        id: 2,
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e18b808f8495cf968480978493a1938490938492cf888f">[email protected]</a>",
        first_name: "Janet",
        last_name: "Weaver",
        avatar: "https://reqres.in/img/faces/2-image.jpg"
    }]

    export default users;

contacts.jsx

import React from "react";
import FilterListIcon from '@mui/icons-material/FilterList';
import { Button, Card, CardActions, CardContent, CardMedia, Typography } from "@mui/material";
import users from "../constants/users";

const Contacts = () => {
    return (
      <div className="parentDiv">
          {
              console.log(users.email,'email') // Result: undefined 'email'
          }
                <div className="header">
                    <h1>Robo Space</h1>
                    <input className="searchFilter" type='text' placeholder="Search here" />
                    <span className="filterIcon"><FilterListIcon /></span>
                </div>
            <div className="body">
            <Card sx={{ maxWidth: 345 }}>
            <CardMedia
              component="img"
              height="140"
                     img={users.avatar}
              alt="robo img"
            />
            <CardContent>
              <Typography gutterBottom variant="h5" component="div">
                {users.first_name}
              </Typography>
              <Typography variant="body2" color="text.secondary">
              {users.last_name}
              </Typography>
            </CardContent>
            <CardActions>
              
              <Button size="small">Show More</Button>
            </CardActions>
          </Card>
                </div>
            </div>
  )
}
export default Contacts;

Answer №1

To retrieve individual properties, simply utilize the dot operator, such as users[0].email. For accessing properties dynamically, employ the .map() method like this:

import React from "react";
import FilterListIcon from '@mui/icons-material/FilterList';
import { Button, Card, CardActions, CardContent, CardMedia, Typography } from "@mui/material";
import users from "./users";

const Contacts = () => {
    return (
      <div className="parentDiv">
          {
              console.log(users[0].email,'email') // Output: undefined 'email'
          }
                <div className="header">
                    <h1>Robo Space</h1>
                    <input className="searchFilter" type='text' placeholder="Search here" />
                    <span className="filterIcon"><FilterListIcon /></span>
                </div>
            <div className="body">
            {users.map((user)=>{
              return (
                <Card sx={{ maxWidth: 345 }}>
                <CardMedia
                  component="img"
                  height="140"
                  src={user.avatar}
                  alt="robo img"
                />
                <CardContent>
                  <Typography gutterBottom variant="h5" component="div">
                    {user.first_name}
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                  {user.last_name}
                  </Typography>
                </CardContent>
                <CardActions>
                  
                  <Button size="small">Show More</Button>
                </CardActions>
              </Card>
              )
            })}
                </div>
            </div>
  )
}
export default Contacts;

For a demo, check out this Sandbox.

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

To ascertain whether the mouse is still lingering over the menu

I have a condensed menu construction that unfortunately cannot be changed in HTML, only CSS and JS modifications are possible! $('span').on("hover", handleHover('span')); function handleHover(e) { $(e).on({ mouse ...

Vertical scroll bar positioned on the left side of a DIV

Can a vertical scroll bar be placed on the left side of a DIV using CSS? What about JavaScript? ...

Suggestions for resolving the issue of my header being truncated on mobile browsers?

I am facing an issue with my header and need assistance in fixing it. The problem occurs when scrolling down, as it cuts off a part of the header, but returns to normal when scrolling back up. I suspect the hamburger menu might be causing this issue becaus ...

Is there a way to dynamically change select2 styling using code when a form is submitted?

Having trouble highlighting empty select2 selects when a form is submitted? I'm struggling to override my existing CSS styling upon document load. Check out my jQuery attempt: var $requiredUnfilledItems = $(".required:not(.filled)"); if ($requiredUn ...

What causes the Text element not to be vertically centered inside the View component?

I recently utilized react-native to design a customized button. The code for the button is shown below: import React, {Component, Fragment} from 'react'; import globalStyles from './../../globals/styles' import { Text, View, ...

Instantaneous data refresh using Firebase Cloud Functions

Currently, I am working on developing a chat feature in React using Firebase cloud functions. However, I am facing an issue where I do not receive updates when a user sends a message. Below is the code snippet that I have been working with: const app = a ...

Setting a default value for Autocomplete in MaterialUI and React.js

Is there a way to set a default value for an Autocomplete TextField component from Material UI in React.js? I want to load a pre-populated value from the user's profile that can then be changed by selecting another option from a list. Check out my co ...

The background image in the header does not fully extend to cover all of the header content

I am currently working on a website for a friend and I am facing an issue with the header section. The header is a div that contains two images inside divs, as well as the company name and slogan in separate divs. The main purpose of this header div is to ...

Utilizing React-hook-Form to transfer data between two SelectBoxes

This simple logic is causing me some trouble. Despite using react-hook-form, I thought this would be easy. However, after struggling with it for over a week, I'm still facing challenges. I'm incorporating nextUI components into my project. < ...

An HTML button generated by a .js file is able to execute a .js function without any issues, but it inadvertently removes all .css styling

Currently grappling with an issue in my JavaScript self-teaching journey that I can't seem to resolve or find examples for. The problem at hand: When the HTML button calls a .js function, it successfully executes the function but also wipes out all C ...

The excessive height of a Bootstrap 5 row is causing the image to overflow beyond the container

I am currently working on setting a maximum height for a banner I am designing in bootstrap5. Here is my code snippet: .banner { background: red; max-height: 50px; } <head> <title>Example</title> <meta charset="utf-8" ...

Leveraging Enum with sec:authorize="hasRole(...)" for user authentication in a Spring Boot and Thymeleaf application

Trying to make a change: <div sec:authorize="hasRole('ADMIN')"></div> to: <div sec:authorize="hasRole(${T(com.mypackage.Role).ADMIN.getText()})"></div> However, the above modification is not working. ...

What is the best way to maintain the position of components (such as a Card component) when one is expanded in a Material-UI and ReactJS project

Currently, I am working with an expandable Card component from Material-UI and using flex for aligning the components. However, when one card expands, it affects the positioning of the other components in the row: https://i.stack.imgur.com/vGxBU.png What ...

Stylish grey container with crisp white lettering

Just getting started with HTML and I've been working on a project for my class. Here's what I've come up with: <font style="background-color: grey; color: white; display: block">Black and white copies $.10 per page letter/legal size&l ...

"Implementing a feature in React JS react-table to dynamically add a new column when a

I'm struggling to add a new column to react-table when a button is clicked. Even after re-rendering the table with a flag, I can't seem to add the new column. Can anyone suggest where I might be going wrong? Here's the link to the executable ...

Issues with manipulating state using TypeScript Discriminated Unions"Incompatibility with setState

Imagine having a unique type structure like the one shown below: export type IEntity = ({ entity: IReport setEntity: (report: IReport) => void } | { entity: ITest setEntity: (test: ITest) => void }); Both the entity and setEntity fun ...

Secure Authentication using JSON Web Tokens in NextJS

After conducting thorough research, I have yet to come across any recent and definitive answers regarding this particular issue. My current project involves implementing JWT authentication within my NextJS application. Here is what I have accomplished so ...

Error message: Uncaught Error encountered in console: Module '/axios' cannot be found at webpackMissingModule while using React

I am currently working on a React app and using axios to handle server requests. However, I keep encountering an error mentioned in the title even though the axios module is clearly present in my package.json file. I have tried uninstalling and reinstallin ...

What is the best way to activate a React MaterialUI dropdown with a single click?

Can you provide guidance on how to open a Material UI dropdown component by clicking the label? <label for="dash-style">Dash style</label> <DropDownMenu id="dash-style" value={this.props.seriesOptions.dashStyle} onChange={this.han ...

Error in NextJS: Attempting to access a length property of null

Does anyone have insights into the root cause of this error? warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works TypeError: Cannot read properties of null (reading 'lengt ...