Home > Blockchain >  console.log shows that the prop has attributes name and number, but they are undefined
console.log shows that the prop has attributes name and number, but they are undefined

Time:06-07

So I have the following code, where I would like to return the number of pages in a book inside of the Part component in the return props.pages. The console.log(props) prints out the attributes of the book (name and pages). However when accessing them in the Part component via props.pages or props.name it returns undefined?

How would I go about fixing this

const Part = (props) => {
  console.log(props);
  return <p>{props.pages}</p>;
};

const Content = (props) => {
  console.log(props);
  return <Part props={props} />;
};


const App = () => {
  const book1 = {
    name: "Harry Potter",
    pages: 108,
  };


  return (
    <div>
      <Content book={book1} />
    </div>
  );
};

export default App;

CodePudding user response:

You've wrapped the "props" in another "props". When you do this:

<Content book={book1} />

The props object in the Content component has a property called book. So when you do this:

<Part props={props} />

The props object in the Part component has a property called props. That property is an object with a property called book. You'd need to reference that property:

return <p>{props.props.pages}</p>;

Alternatively, you can pass the values more explicitly instead:

<Part pages={props.pages} />

Or spread the properties of the props object to implicitly pass all of them:

<Part {...props} />

In either of these cases you'd be able to access the property directly:

return <p>{props.pages}</p>;

CodePudding user response:

Try this :

const Part = (data) => {
  const { props } = data;
  return <p>{props.book.pages}</p>
};

Demo : https://codesandbox.io/s/vigorous-jepsen-lqjs01?file=/src/App.js:24-113

  • Related