Tips for utilizing an array within React and transforming it into a component

I've developed a website that pulls data from a SQL database I created, containing details such as name, address, and occupation of individuals. I successfully managed to showcase this information on the webpage by structuring an array and inserting the data into it for retrieval. My goal now is to design a React component resembling a tile or nametag box that displays each person's name and job role separately for every entry. However, I am uncertain about how to create the React component and apply CSS styling to it.

Here is the code snippet for my webpage:

    import React, { Component } from "react";

export class Dashboard extends Component {
    displanyName = Dashboard.name;

    constructor(props) {
        super(props);

        this.state = {
            people: []
        };
    }

    componentDidMount() {
        fetch("api/people")
            .then(response => response.json())
            .then(data => this.setState({ people: data }));
    }
    render() {
        //const { people } = this.state; // equivalent to next line
        const people = this.state.people;
        if (people.length > 0)

        //creates an array to iterate
        let arr = people.map((person, index) => <div key={index}>Person: {person.name} , Job: {person.job}</div>);

        return (
            <div>
                {arr}
            </div>
        );
    }
}

This code snippet showcases the array contents on the page in the following format: Person: Bob Bobbert , Job: Programmer Person: Jane Doe , Job: Teacher Person: John Smith , Job: Chef

Answer №1

If my understanding is correct, you can give this a try.

import ReactDOM from 'react-dom';
import React, { Component } from 'react';

export class PersonNameJob extends Component {
  render() {
    return (
      <div style={{ fontWeight: 'bold' }}>Person: {this.props.person.name}, Job: {this.props.person.job}</div>
    );
  }
}

export class Dashboard extends Component {
  // add more code here...
  render() {
    const people = [
      {
        name: 'John',
        job: 'Developer',
      },
      {
        name: 'Marry',
        job: 'accountant',
      },
    ];

    return (
      <div>
        {people.map((person, index) => (<PersonNameJob key={index} person={person} />))}
      </div>
    );
  }
}

ReactDOM.render(
  <React.StrictMode>
    <Dashboard />
  </React.StrictMode>,
  document.getElementById('root')
);

You have the option to directly style using the style attributes of a Component or utilize the styled-components package for styling.

export class Dashboard extends Component {
  render() {
    // logic for fetching people
    return (
      <div>
        {people.map((person, index) => (<StyledPersonNameJob key={index} person={person} />))}
      </div>
    );
  }
}
const StyledPersonNameJob = styled(PersonNameJob).`
    background-color: red;
    border: 1px solid #000;
`;

Answer №2

If you're considering a different approach, have you explored the benefits of incorporating Material UI? Material UI is my preferred choice for handling tasks like this. The Card Component offers a simple solution to create what you need effortlessly. To implement Material UI, you'll need to install it using npm install @material-ui/core or yarn add @material-ui/core. Once installed, you can start utilizing the components in your project. Here's an example:

import React, { Component } from "react";
// Import material UI card components
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
// Useful component for displaying text - various variants (body, h1, h2, etc.)
import Typography from '@material-ui/core/Typography';

export class Dashboard extends Component {
    displanyName = Dashboard.name;

    constructor(props) {
        super(props);

        this.state = {
            people: []
        };
    }

    componentDidMount() {
        fetch("api/people")
            .then(response => response.json())
            .then(data => this.setState({ people: data }));
    }
    
    render() {
        //const { people } = this.state; // equivalent to next line
        const people = this.state.people;
        
        if (people.length > 0) {
            // Create an array to iterate
            let arr = people.map((person, index) => (
                <Card key={index}>
                    <CardContent>
                        <Typography variant="h5">
                            Person: {person.name}
                        </Typography>
                        <Typography variant="body2"> 
                            Job: {person.job}
                        </Typography>
                    </CardContent>
                </Card>
            ));
            
            return (
                <div>
                    {arr}
                </div>
            );
        }
    }
}

Material UI provides thorough documentation (linked above) with complete code samples to showcase how everything can be utilized and integrated into your components. If you encounter challenges with the visual appeal of your components like I do, I highly recommend exploring the capabilities of Material UI.

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

How to Calculate the Time Interval Between Two CORS Requests Using jQuery AJAX

When using jQuery's $.ajax to make a CORS request to a web service, there is typically a pre-flight request followed by the actual POST request. I have observed that when there is a time gap between making two web service calls, both a pre-flight and ...

I've encountered some issues with importing pagination from modules after installing SwiperJs

Having some issues with importing pagination from modules in SwiperJs for my nextjs project. The error message "Module not found: Package path ./modules is not exported from package" keeps popping up. I have tried updating the module to the latest version ...

Issue arising from background change upon component focus

My component needs to change its background color when focused, but for some reason it's not working. The hover effect works fine, but the focus doesn't. Can anyone assist me with this issue? import { CardContainer } from './styles' in ...

Issue encountered while trying to implement a recursive function for mapping through nested elements was not producing the

I am currently working on recursively mapping through an array of nested objects, where each object can potentially contain the same type of objects nested within them. For example: type TOption = { id: string; name: string; options?: TOption; } con ...

Aligning content with CSS styling

I am facing a challenge with aligning buttons in three different td tags, as the text content within each varies. I want the buttons to line up evenly regardless of the amount of text present. Is there a solution that does not involve setting a fixed parag ...

Showing nested arrays in API data using Angular

I would like to display the data from this API { "results": [ { "name": "Luke Skywalker", "height": "172", "mass": "77", & ...

What are the solutions for fixing a JSONdecode issue in Django when using AJAX?

I am encountering a JSONDecodeError when attempting to send a POST request from AJAX to Django's views.py. The POST request sends an array of JSON data which will be used to create a model. I would greatly appreciate any helpful hints. Error: Except ...

Eliminate duplicate items using the reduce method in JavaScript

Working with a set of Json Objects, I use a javascript map function to list each field along with an array of its possible types. For example: birthDate, [Date, String, String, String, String] isMarried, [Boolean, Boolean, Boolean, Boolean, String] name, ...

Unable to locate the value of the query string

I need help finding the query string value for the URL www.example.com/product?id=23 This is the code I am using: let myApp = angular.module('myApp', []); myApp.controller('test', ['$scope', '$location', '$ ...

html form shifting positions based on screen resolution

I have been experimenting with a login screen design for my website recently. I created a form with a fixed position, but as the screen resolution changes, not only does the form's position shift, but also the image moves, causing an unwanted interse ...

An error alert pops up when I attempt to generate a react application, preventing me from proceeding

Attempting to create a new React app with the command 'npx create react-app rcsg' resulted in an error message stating "npm ERR! could not determine executable to run." ...

What could be causing the issue with HTML not being printed upon button click in ReactJS?

My goal is to display the word "Hello" on the screen when the add button is clicked. However, I am encountering an issue where it is not showing up. Any insights or solutions would be greatly appreciated! import React, { Component } from 'react'; ...

Codeigniter session unexpectedly ends after AJAX call completes successfully

Currently, I am utilizing the CodeIgniter framework on a Heroku server with an AWS database. In my AJAX success function, I have a window.location.reload(); call which ends up destroying the session and redirecting to the login page. Is there a way to prev ...

A scenario in a Jasmine test where a function is invoked within an if statement

My coding dilemma involves a function: function retrieveNames() { var identifiers = []; var verifyAttribute = function (array, attr, value) { for (var i = 0; i < array.length; i++) { if (array[i][attr] === va ...

What is the method to initialize a Stripe promise without using a React component?

I have encountered an issue while implementing a Stripe promise in my React app. The documentation suggests loading the promise outside of the component to prevent unnecessary recreations of the `Stripe` object: import {Elements} from '@stripe/react-s ...

Combining the power of jQuery, PHP, JavaScript, and the popular WordPress platform, let's unlock

After going through numerous attempts to find answers for similar issues, I'm unable to get any of the suggested solutions to work. My WordPress site requires a plugin that utilizes jQuery. The main file for my plugin is located at wp-content/plugins ...

What is the best way to make an element disappear 5 seconds after the mouse has stopped hovering

#section1 { display: block; } #section2 { display: none; } #container:hover > #section2 { display: block; } <div id="container"> <div id="section1">Section1</div> <div id="section2">Section2</div> </div> ...

The periodLookup array does not have a defined value for periodStr. Why is this error being caught?

Here is a method that I am working with: set_period_help_text: function(periodInput){ var metric = MonitorMetric.getSelectedMetric(); var periodStr = $('select[name=metric_period]').val(); var datapoints = Number(periodIn ...

Loop through each row in the Datatable and access the details or child

I need to iterate through each child row in a datatable. For example, if I have AJAX data structured like this: "data": [ { "date" : "1/17/2016", "supplier" : "supplier1", "total" : "$10", "payment" : "Cash", "product" : Array[2] ...

Generate additional tabs

Currently, I am in the process of working on a project where I have a bar that will contain dynamically filled tabs. My goal is to include a (+) image that becomes visible when the bar is full. When a user clicks on this image, the remaining tabs should ap ...