Home > Blockchain >  React components inside each other
React components inside each other

Time:07-13

I am learning React and while doing that, I am trying to build my simple project. To create some kind of a bookstore, which is made up by shelves and I want books to be inside these shelves.

My Index.js is unchanged ~ created by npx create-react-app

App.js:

import Bookstore from './components/BookStore';

function App() {
    return <Bookstore />;
}

export default App;

Shelf.js

import React from 'react';
import '../css/shelf.css';

function Shelf() {
    return <div className="shelf-div"></div>;
}

export default Shelf;

Book.js

import React from 'react';
import '../css/book.css';

function Book() {
    return <div className="book-div"></div>;
}

export default Book;

Bookstore.js

import React from 'react';
import Book from './Book';
import Shelf from './Shelf';

function Bookstore() {
    return (
        <div>
            <Shelf>
                <Book />
                <Book />
                <Book />
            </Shelf>
            <Shelf />
        </div>
    );
}

export default Bookstore;

Now my app is only displaying the Shelves, even though I expected it to display the books inside the first shelve, which didn't work. I tried to add the books right in the Shelve.js file, which works but displays same books on every shelf, but logically I want each shelf to contain different books, so I want to add them in the Bookstore.js. The css is currently just rectangles for shelves and smaller rectangles for books.

Thank you for your help.

CodePudding user response:

Update your Shelf.js as follows:

import React from 'react';
import '../css/shelf.css';

function Shelf(props) {
    return <div className="shelf-div">{props.children}</div>;
}

export default Shelf;

Also, check out the official documentation:

Some components don’t know their children ahead of time. We recommend that such components use the special children prop to pass children elements directly into their output.

CodePudding user response:

if you want to render the books you need to access it as props. Change your Shelf into this one.

function Shelf(props) {
    return <div className="shelf-div">{props.children}</div>;
}
  • Related