0

I am trying to reach some nested values within an object in my API. I am also trying to pass these values as props from the child component to the parent component.

Everything works but I can't display any value within "address" and "company".

I am trying with {address.name} and {adress[0].name} but I get errors with both.

I would like to print street, suite, city, and zip code.

This is my API:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },

This is what I am returning within the parent component:

return (
    <>
      <header>      
        <h1>Users list</h1>
      </header>
      <section> 
        <ul>
          {users.map(user => (
            <li key={user.id}>
              <button onClick ={() => setSelectedUser(user)}>{user.name}</button></li>
          ))}         
        </ul>

        {selectedUser && (
          <UserDetail 
            name={selectedUser.name} 
            username={selectedUser.username}
            email={selectedUser.email}
            adress={selectedUser.adress.street}
            phone={selectedUser.phone}
            company={selectedUser.company.name}
          />)}
      </section>
    </>

This is what I am passing from the child comp:

const UserDetail = ({name, username, email, adress, phone, website, company}) => {
  return (
    <div>
      <h1>{name}</h1>
      <p>{username}</p>
      <p>{email}</p>
      <p>Adress:{adress.street}</p>
      <p>{phone}</p>      
      <p>{website}</p>      
      <p>{company.name}</p>      
    </div>
  )
}

export default UserDetail

1 Answer 1

1

the response contains address but you are using with a single s selectedUser.adress. For company you are passing the company name as props so you don't have to do again company.name but just company.

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

2 Comments

Thank you Antonio, the props are ALWAYS passed from parent to child right?
yes. and it is updated every time you click on the button because you are changing one state of the component. I guess you are using const [selectedUser, setSelectedUser] = useState(); to keep track of the selected user, right ?

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.