1

I am able to fetch REST API where I can get nested json output, and I want them to display in React component. Now I only can render them in the console which is not my goal actually. I am wondering if there is an efficient way to do this for rendering nested json list in React. can anyone give me a possible idea to make this work?

here is what I did:

import React, { Component } from "react";

class JsonItem extends Component {
  render() {
    return <li>
      { this.props.name }
      { this.props.children }
    </li>
  }
}

export default class List extends Component {
  constructor(props){
    super(props)
    this.state = {
    data: []
    }
  };   
  componentDidMount() {
      fetch("/students")
      .then(res => res.json())
      .then(json => {
          this.setState({
          data: json
          });
      });
  }
  list(data) {
    const children = (items) => {
      if (items) {
        return <ul>{ this.list(items) }</ul>
      }
    }
    return data.map((node, index) => {
      return <JsonItem key={ node.id } name={ node.name }>
        { children(node.items) }
      </JsonItem>
    });
  }
  render() {
    return <ul>
      { this.list(this.props.data) }
    </ul>
  }
}
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

my current output:

in my above component, I could render nested list on the console like this:

[![enter image description here][1]][1]

desired output:

how can I properly render out nested json output on React? Any idea to make this happen? any thought? Thanks

2 Answers 2

3

As you knew .map() is the common solution for this. But you can make this much better like below.

export default class List extends Component {
  constructor(props){
    super(props)
    this.state = {
      data: [],
      isLoaded: false,   //initally the loading state is false.
    }
  };

  componentDidMount() {
      fetch("/students")
      .then(res => res.json())
      .then(json => {
          //updating the loading state and data. 
          this.setState({data: json, isLoaded:true}); 
      });
  }

  render() {
   //Waiting ajax response or ajax not yet triggered.  
   if(!this.state.isLoaded){
     return(<div>Loading...</div>);
     }else{
       //Rendering the data from state.
       let studenDetails = this.state.data.map((student, i) => {
         let uin = student.uin; 
         let studentInfo = Object.keys(student.studentInfo).map((label, i) => {
         return (
            <div key={i}>
              <span>
               <strong>{label}: </strong>{`${student.studentInfo[label]}`}
              </span>
            </div>
         );
        });
        return (
         <div key={i}>
           <h3>{uin}</h3>
           <p>{studentInfo}</p>
          </div>
        );
       });
      return (<div>{studenDetails}</div>);
     }
    }
   }

Hope it will help you.

Sign up to request clarification or add additional context in comments.

8 Comments

give me a min. let me update the answer. @beyond_inifinity
if you are able to compile your solution with a fully working example on the fiddle that would be a big plus. Thanks
Updated the answer. @beyond_inifinity
How can I do collapse or expand student info for rendering? like accessing uin and studentinfo? Can you guide me? Thanks for your awesome solution.
Do you need only collapse/expand with sort by uin? or more. If you need more you can simply render that information inside RectTable it will take care of search, sorting and pagination. @beyond_inifinity
|
0

To render a list in react use the .map() function to build a list of jsx elements.

render() { 
  let myRenderedData = this.state.data.map((x, index) => {
    return <p key={index}>{x.uin}</p>
  })
  return (<div>{myRenderedData}</div>)
}

8 Comments

you're missing the key key={x.someUniqueKey}
@Gonzalo.- can you provide fully working example instead? thanks
@beyond_inifinity and no, you don't need to use the JsonItem component to render a list.
Well if you tell me what error you're getting I might be able to help you. There's nothing wrong with this answer, assuming uin exists as a property on your data set. If you want to display other fields do x.studentInfo.firstName and so on.
@beyond_inifinity okay, but what does the error message say? I cant do everything for you. Im not psychic. I updated answer to try to make it easier to understand.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.