Home > Back-end >  How to access the individual contents of a nested object(state form) in React?
How to access the individual contents of a nested object(state form) in React?

Time:09-30

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: 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.

CodePudding user response:

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}
  • Related