2

I'm new to reactjs and trying to build a basic ui by parsing a json object.

class App extends Component {

  state ={
    products : []
  };
render() {
    return (
      <div>
        <Form onSubmit = {this.addNewProducts}/>
        <ProductList products = {this.state.products} />
      </div>
    );
  }
}

const ProductList =(props) => {

  return(
    <div>
      {props.products.map(product => <Product {...product}/>)}
    </div>
  );
}

Trying to render some of the data from json here, which is where I'm struggling with. Tried to use Map but no luck, at least I'm not using it correctly.

const Product = (props) => {
  return(
    <div>
      <div>
        {props.pludetails}</div>
    </div>
  );
};

Returning JSON object:

{
    "ResultCode": 0,
    "ResultDescription": "Success",
    "pludetails": [
        {
            "UPC": 490000129,
            "ItemDesc": "SPRITE",
            "Department": 197,
            "Price1": 7.99,
        }
    ]
}
Raj
  • 23
  • 1
  • 4
  • You are trying to display object. You can’t do something like that html accept only string this mean you need to try to display property instead of object – Sider Topalov Apr 26 '18 at 16:08
  • pludetails is also an array of object, check this https://stackoverflow.com/questions/41374572/how-to-render-an-array-of-objects-in-react/41374730#41374730 – Shubham Khatri Apr 26 '18 at 16:12
  • Yes, I was getting errors for displaying object. – Raj Apr 26 '18 at 17:01

1 Answers1

1

Now you just render js object as React child, but you need to write render function for pludetails.

Here is short example:

const Pludetails = (props) => {
 return(
   <div>
    <span>{props.UPC}</span>
    <span>{props.ItemDesc}</span>
    <span>{props.Department}</span>
    <span>{props.Price1}</span> 
   </div>
 );
}

In Product :

const Product = (props) => {
  return(
    <div>
      <div>
        {props.pludetails.map((item, i) => <Pludetails key={i} {...item}/>)}
      </div>
    </div>
  );
};

In ProductList add key prop, for reduce key errors:

const ProductList =(props) => {

  return(
    <div>
      {props.products.map((product, i) => <Product key={i} {...product}/>)}
    </div>
  );
}

Use indexes by keys width dynamic data is danger. You can use id or something else what you wont.

Artem Mirchenko
  • 2,140
  • 1
  • 9
  • 21
  • Thanks Artem. That did the trick. Good learning for me to handle the multi-level json. – Raj Apr 26 '18 at 16:57