Home > Blockchain >  Can you render an object inside an object?
Can you render an object inside an object?

Time:12-07

I'm not sure how I would select this data if it's possible: Console Data, I am trying to select the data within the 'posts' table, since I have relations setup for the users table & posts table

This is how I usually render the data.

    render() {
        console.log(this.state.postData);
        if (this.state.postData.length === 0) {
            return <div>Profile data not found</div>
        }

        const dashPost = this.state.postData.map(post => (
            <div key={post.UserId}>
                <h1>{post.FirstName}</h1>
            </div>
        ));

        // Jquery animations can go here

        return <div>{dashPost}</div>
    }

I am wondering if it's possible to render the post data that comes with the user.

I decided to give this a try, but I figured it wouldn't work.

{post.posts.PostTitle}

I've came across this forum: React & Axios - Get values from an object inside of an object

BUT I have no idea how to actually implement it.

CodePudding user response:

Yes, you can render an object inside an object in React.js by using the React.createElement() method to create a new React element from the object, and then rendering that element inside the parent object.

Here is an example of how you could do this:

const myObject = {
        name: 'My Object',
        description: 'This is my object',
      };

          const parentObject = {
        name: 'Parent Object',
        description: 'This is the parent object',
        children: [
          React.createElement('div', {}, myObject.name),
          React.createElement('div', { }, myObject.description),
        ],
      };

      // Render the parent object
      ReactDOM.render(
        React.createElement(
          'div',
          { },
          React.createElement('div', { }, parentObject.name),
          React.createElement('div', { }, parentObject.description),
          parentObject.children,
        ),
        document.getElementById('root')
      );

In this example, the myObject is rendered inside the parentObject, and the parentObject is then rendered on the page using the ReactDOM.render() method. You can use this technique to render any number of objects inside a parent object.

CodePudding user response:

Looking at this.state.postData from image, post.posts is an Array. Try {post.posts[0].PostTitle} to get PostTitle of posts at index 0 or use post.posts.map to render the array of posts again.

So your code would look something like this -

const dashPost = this.state.postData.map(post => (
   <div key={post.UserId}>
       <h1>{post.FirstName}</h1>
        {
          post.posts.map(p => {
             <p>{p.postTitle}</p>
          })
        }
   </div>
));
  • Related