Map dictionary keys to rows and display its values

Tags: ,



I have a list of dictionaries set as props in my React component, like so:

console.log(fruits): [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ] 

The dicts:

0:
name: 'Apple'
color: 'Red'

1:
name: 'Banana'
color: 'Yellow'

2:
name: 'Pear'
color: 'Green'

....

And I need to display their NAMES in the rows, each row based on a respective fruit color:

class Basket extends Component {
  constructor(props) {
    super(props);

    this.state = {
      fruits:[],
      isLoaded:false
    };
  }

render() {

        const { fruits } = this.props;
        console.log(fruits)

        return (
     <div className="app">
        <div className="fruit-wrapper">
          <div className="row">
            <Fruit>Apple</Fruit>
            <Fruit>Red 2</Fruit>
            <Fruit>Red 3</Fruit>
          </div>
          <div className="row">
            <Fruit>Banana</Fruit>
            <Fruit>Yellow 2</Fruit>
            <Fruit>Yellow 3</Fruit>
          </div>
            <div className="row">
            <Fruit>Pear</Fruit>
            <Fruit>Green 1</Fruit>
            <Fruit>Green 2</Fruit>
          </div>
          </div>
        </div>
      </div>
    );
  }

export default Basket;


How can I map fruit object values from this list os dicts and display fruit names assigning each name to its respective row color?

Answer

Working sandbox

import React from "react";

function Fruit({ children }) {
  return <div>{children}</div>;
}

export default class Basket extends React.Component {
  state = {
    isLoaded: false
  };

  render() {
    const { fruits } = this.props;

    return (
      <div className="app">
        <div className="fruit-wrapper">
          {fruits.map(({ name, color }) => (
            <div className="fruit-wrapper">
              <Fruit>{name}</Fruit>
              <Fruit>{color} 2</Fruit>
              <Fruit>{color} 3</Fruit>
            </div>
          ))}
        </div>
      </div>
    );
  }
}


Source: stackoverflow