0

I'm working with React 16 and my goal I'm trying to render an array from a JSON file, I'll appreciate any help.

JSON: trying to render a list of codigoLote

{ 
"_id" : "bMv7ip59zuy3PyTvD", 
"codigo" : "001", 
"name" : "Nombre 1", 
"lab" : "Lab 2", 
"principio" : "activo", 
"dosis" : "dos", 
"sintomas" : "tres", 
"contra" : "cuatro", 
"createdAt" : ISODate("2017-11-05T19:12:19.628Z"), 
"Lotes" : [
{ "codigoLote" :"B4578", "cantidad" : "100", "costo" : "0.00", 
  "fIngreso" : "7/11/2017", "fVence" : "7/11/2017" }

{ "codigoLote" :"B4579", "cantidad" : "100", "costo" : "0.00", 
  "fIngreso" : "7/11/2017", "fVence" : "7/11/2017"}
 ] }

I tried this but React won't render it with this error: Uncaught Error: Objects are not valid as a React child (found: object with keys {codigoLote, cantidad, costo, fIngreso, fVence}). If you meant to render a collection of children, use an array instead.

<Row>
    {this.props.meds.Lotes}
</Row>

I tried this solution as well, but it doesn't seem to find my the fields on the array.

  var ListRender = React.createClass({
    render: function() {
      return (
        <ul>
          {this.props.meds.Lotes.codigoLote(function(listValue){
            return <li>{listValue}</li>;
          })}
        </ul>
      )
    }
  });

. . .

<Row>
    <ListRender />
</Row>
Edwin Barahona
  • 189
  • 1
  • 3
  • 13

1 Answers1

2

What are you expecting the end result to be? You have an array of objects. You need to loop through that array of objects, then for each object, look through him and spit out each key-value pair as an <li> formatted however you want. Maybe something like:

  <ul>
    {this.props.meds.Lotes.map((lotesObject) => (
      Object.entries(lotesObject).map(([key, value]) => (
        <li>{key}: {value}</li>
      ))
    ))}
  </ul>

Edit: You'd actually probably be better off making each object his own <ul>, plus whatever else you may wanna do inside:

  <div>
    {this.props.meds.Lotes.map((lotesObject) => (
      <ul>
        {Object.entries(lotesObject).map(([key, value]) => (
          <li>{key}: {value}</li>
        ))}
      </ul>
    ))}
  </div>
SamVK
  • 3,077
  • 1
  • 14
  • 19
  • I tried the above but it comes back with `Uncaught TypeError: Cannot read property 'map' of undefined`. I'm a bit lost here, how should I initialize it? – Edwin Barahona Nov 08 '17 at 15:06
  • Why is `this.props.meds.Lotes` ever undefined? Is the data being returned by an API at some point and possibly not loaded yet? – SamVK Nov 08 '17 at 19:17