1

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

3 Answers 3

1

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;
`;
Sign up to request clarification or add additional context in comments.

4 Comments

Would this method involve putting this code within the same file as dashboard or as separate files like PersonNameJob.js and PersonNameJob.css?
If the PersonName component is small, you can put it in the same file with Dashboard. Otherwise, you should define a component each file. CSS should be defined in the component.
One more thing, you should consider using Functional Component instead of Class Component. Because React Hooks may has better performance but they are designed for Functional Component only. reactjs.org/docs/hooks-intro.html
I tired putting this part above what I had already written ``` import React, { Component } from 'react'; export class PersonNameJob extends Component { render() { return ( <div key={index} style={{ fontWeight: 'bold' }}>Person: {this.props.person.name} , Job: {this.props.person.job}</div> ); } } ``` But now I receive this error "Line 7:23: 'index' is not defined no-undef"
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.