Tramsey
Tramsey

Reputation: 21

How to use an array in React and convert to component

I've created a webpage that pools from a SQL database I generated that has info such as a person's name, address and job. I figured out how to display this on the webpage by creating an array and putting the data into it to then return. What I want to do is create a react component that looks like a tile/nametag and is a box containing each person/job and have it be created for each entry. I am confused on how I would create the react component and style it with CSS.

here is my webpage code:

    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>
        );
    }
}

That displays the contents of the array on the page like this: Person: Bob Bobbert , Job: Programmer Person: Jane Doe , Job: Teacher Person: John Smith , Job: Chef

Upvotes: 1

Views: 760

Answers (3)

Shariati
Shariati

Reputation: 119

your question is looking similar to rendering dynamic components on the fly. checkout this https://gist.github.com/arifshariati/c607a2baf87976f8a2a2ce61c988db4f for dynamic rendering.

for complete example, checkout dynamic form rendering in React and Material UI here https://github.com/arifshariati/react-dynamic-form-drag-drop-redux

Upvotes: 0

Tomanator
Tomanator

Reputation: 28

Have you thought about using Material UI? I like to use material UI for things like this. The Card Component could be used to easily make what you are looking for. To use material UI you will need to install it using npm install @material-ui/core or yarn add @material-ui/core. You can then use the components in your components. It would look something like this:

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 - multiple 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)

        //creates 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 has great documentation (linked above) with full code samples so you can see exactly how everything can be used and how it fits in to your components. I would recommend it if, like me, you struggle a bit with the UI look of components.

Upvotes: 0

Quỳnh Nguyễn
Quỳnh Nguyễn

Reputation: 465

If I understand correctly, you can try this.

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 {
  // 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 can style directly by using style attributes of a Component or use styled-components package.

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

Upvotes: 1

Related Questions