Raj
Raj

Reputation: 23

Parsing JSON object in reactjs

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,
        }
    ]
}

Upvotes: 2

Views: 9053

Answers (1)

Artem Mirchenko
Artem Mirchenko

Reputation: 2170

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.

Upvotes: 1

Related Questions