dante
dante

Reputation: 1111

props destructuring in react

I have component props looks like

**props**
{
  banner : {
    logo: "...",
    banner: "..."
  },
  content, 
  ...
} 


I grab this props like this

const MyComponent = (props) => {
  const { 
    banner: { logo, title },
    content
  } = props; 
  ... 
  function someFunction(){
    if( banner.logo) {. // <- banner is undefined
      if(title) // <- this title works 
    }
   ... 
  }
  ... 
}

I tried to destructuring props object and use all of these banner, content, logo, title

but compiler complains banner as undefined. Am I doing wrong about destructuring ?

Upvotes: 0

Views: 117

Answers (2)

Jesus Pacheco
Jesus Pacheco

Reputation: 53

Simple, you are not taking the banner variable from the props actually, you are taking title and logo instead.

You can do this:

const MyComponent = (props) => {
  const { 
    banner,
    content
  } = props; 
  ... 
  function someFunction(){
    if( banner.logo) {
      if(banner.title)
    }
   ... 
  }
  ... 
}

Upvotes: 0

hangindev.com
hangindev.com

Reputation: 4873

When you are destructuring objects like the following, only logo, title and content are unpacked.

  const { 
    banner: { logo, title },
    content
  } = props; 

That's why inside someFunction in your question, you could just do:

function someFunction() {
  if (logo) {
  ...
    if (title) {
    ...
    }
  }
}

If you also want to use the variable banner, you have to do the following:

const { banner, content } = props;
const { logo, title } = banner;

Read more about Destructuring assignment

Upvotes: 1

Related Questions