Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access the individual contents of a nested object(state form) in React?

I have a nested object that is usually rendered when I have finally transferred the state through navigation (transferring the product items to the payment page).

This question is a continuation from my previous question for the logic of my shopping cart functionality:
How to transfer product items to the payment page after clicking the checkout button in React?

Main Goal: I have to access the content values of the nested object and transform these values into a much more readable form by displaying the individual contents of them. I have to access the individual value of totalPrice and access the values of the inner object cartItems

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Problem: Even after using Object.keys(obj).map((key) => () functionality, it doesn’t display the individual values of the nested object such as the totalPrice and the inner object cartItems. Currently, I only did a JSON.stringify(obj) to display its nested object form so I can see it temporarily.

Nested object appearance currently:.

nested object pic

Goal appearance:
goal appearance

Source code from PaymentPage.jsx (where I did the Object.keys functionality):

import React from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useNavigate,
  useLocation
} from "react-router-dom";

export default function PaymentPage(props) {
  const navigate = useNavigate();
  const location = useLocation();
  const navigateToHomeOrderPage = () => {
    navigate("/");
  };

  const data = location.state;  //the passed object being used

  return (
    <aside className="block col-1">
      <button
        sx={{ width: 10 }}
        style={{ maxWidth: "60px" }}
        onClick={navigateToHomeOrderPage}
      >
        Go back
      </button>
      <h2>PAYMENT PAGE</h2>
      {/* {JSON.stringify(data)} */}

            {/* Temporary object display:  */}
      <pre sx={{ ml: 120 }}>{JSON.stringify(data)}</pre>

      {/* {Object.keys(data).map((key) => (
          <h3>
            {key}: {data[key]}
          </h3>
        ))}

        ERROR: Objects are not valid as a React child (found: object with keys {id, name, price, image, qty}). If you meant to render a collection of children, use an array instead.
        
        */}
      {/* 
      {Object.keys(data).map((keys) => {
        return <h1>{data[keys].name}</h1>;
      })} 

      No errors but notihng is displayed
      
      */}
    </aside>
  );
}

Full functioning App in CodeSandbox:
https://codesandbox.io/s/react-access-nested-object-forked-5xvp2x?file=/src/components/PaymentPage.jsx

Hoping for your guides and responses on this one since I am very much confused on how to access nested objects in React. Your guides, responses, and tweaks would indeed help me a lot on this one in gaining the logic out of it.

>Solution :

If your data object structure its going to be the same you can do it like this example:

{data?.cartItems.map((item ,index) =>
  <div key={index} style={{display:'flex', gap:'8px '}}>  
  <img src={item.image} style={{height:'100px', width:'100px'}} />
  <p>{item.name}</p>
  <p>{item.price}</p>
  <p>{item.qty}</p>
  </div> 
)}
TOTAL: {data?.totalPrice}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading