Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React array of components not mapping

Tags:

arrays

reactjs

So I am trying to loop through some components so that I can keep track of the component height in order to decide to put a page break. I have an array of components that I am trying to map but I am getting the infamous map is not a function. Here is my code.

import React, { Component } from "react";
import styled from "styled-components";
import sizeMe from "react-sizeme";

const WhiteRow = styled.div`
  background-color: #ffffff;

  &:after {
    content: "";
    width: 100%;
    height: 100%;
    left: 0px;
    top: 0px;
    background-color: transparent;
    box-shadow: 0 2px 52px -20px rgba(132, 133, 122, 0.5);
    position: absolute;
    z-index: 0;
  }
`;

const P = styled.p`
  margin: 0;
`;

class RoomPage extends Component {
  render() {
    const { data, globalData } = this.props;
    // console.log(data)
    return (
      <div>
        {ReportItems.map(items => (
          <div>{items.comp}</div>
        ))}
      </div>
    );
  }
}
export default sizeMe({ monitorHeight: true })(RoomPage);

const RoomPageHeader = ({ data }) => (
  <div>
    <P>{data.created_at}</P>
    <div>
      <h5>
        <strong>{data.content.title}</strong>
        <strong>Observations</strong>
      </h5>
      <P>
        {data.content.address.address1}
        {data.content.address.address2} <br />
        {data.content.address.city} {", "}
        {data.content.address.state} {data.content.address.zipcode}
      </P>
    </div>
  </div>
);

const RoomBar = ({ data }) => (
  <div>
    <P>
      Room: <strong>{data.room.label}</strong>
    </P>
  </div>
);

const ReportItems = ({ data }) => [
  {
    comp: <RoomBar data={data} />
  },
  {
    comp: <RoomBar data={data} />
  }
];

Would appreciate any help. I consoled out the ReportItems const and I get back the array of objects with the components.

like image 933
Tyler Nichol Avatar asked Mar 03 '23 19:03

Tyler Nichol


2 Answers

Like i was saying in the comments. Just call the function first, pass the data through so your components get that prop, then map over it.

render() {
  const { data, globalData } = this.props;
  const items = ReportItems({data})
  return (
    <div>
      { items.map(
          (items) => items.comp
        )
      }
      </div>
  );
}

Demo!

Not really sure what your goal / approach is though. If you just want to render a component a few times you can just do that directly without putting an instance inside an array like this.

like image 52
John Ruddell Avatar answered Mar 25 '23 05:03

John Ruddell


Just change it this way:

{ReportItems().map(items => <div>{items.comp}</div>)}
//----------^^

Also get rid of the ; at the end.

like image 35
Praveen Kumar Purushothaman Avatar answered Mar 25 '23 05:03

Praveen Kumar Purushothaman