YvonC
YvonC

Reputation: 349

React - Trying to render property of object, though it stays "undefined"

console.log(detailtext) shows me that the data of the object is there, the props seem to work, but I can't display the properties of the object. Why?

It's a very simple component:

import React from "react";
import { Link } from "react-router-dom";

class LibraryTextDetails extends React.Component {
  render() {
    const detailtext = this.props.detailview || {};
    console.log("THIS IS THE DETAILTEXT");
    console.log(detailtext);
    const detailviewIds = detailtext.id;
    console.log("THIS IS THE DETAILVIEW ID");
    console.log(detailviewIds);

    return (
      <div>
        <div className="covercard">
          <img
            src={detailtext.lead_image_url}
            width={157}
            className="coverdetailimage"
          />
        </div>
        <div className="titledetailcard">{detailtext.title}</div>
        <div className="authordetailcard">{detailtext.author}</div>
      </div>
    );
  }
}

export default LibraryTextDetails;

Here is the console.log:

enter image description here

Upvotes: 0

Views: 3119

Answers (2)

Tholle
Tholle

Reputation: 112917

You are passing in an array as detailview to your component. The data you see in your console is the data of the first object in the array. Make sure you render detailview[0], and it will work.

Example

class LibraryTextDetails extends React.Component {
  render() {
    const { detailview } = this.props;
    const detailtext = (detailview && detailview[0]) || {};

    return (
      <div>
        <div className="covercard">
          <img
            src={detailtext.lead_image_url}
            width={157}
            className="coverdetailimage"
          />
          <div className="titledetailcard">{detailtext.title}</div>
          <div className="authordetailcard">{detailtext.author}</div>
        </div>
      </div>
    );
  }
}

Upvotes: 2

AlexGvozden
AlexGvozden

Reputation: 457

you are missing important thing

detailtext is array of objects

when you see in log [{ ... }] it means it's Array with one object

log also displays first object in array below

so correct use would be

detailtext[0].lead_image_url
detailtext[0].title

and similar or use proxy variable or fix the way you send data to this component not to be array but just an object (first in array)

Upvotes: 0

Related Questions