Reputation: 285
I am trying to build a simple app that fetches books from google books API. I have a Body component with a search bar that renders a BookDisplay
component that maps an array of books into BookCard
s. Each card has a Learn More
button which should open a modal with all the book info and here is where I get stuck. How do I pass the book info to the BookModal
component?
Here is an example of my actual BookDisplay class
import style from './booksdisplay.module.css'
import BookCard from "../BookCard/BookCard";
import BookModal from "../BookModal/BookModal";
function BooksDisplay(props) {
const books=props.books
if(books.length===0){
return(
<div>{props.message}</div>
)
}
else{
return (
<div className='Books'>
<div>{props.message}</div>
{
books.map(book=>{
return (
<BookCard data={book.volumeInfo}/>
)
})
}
<BookModal/>
</div>
)
}
}
export default BooksDisplay
Here is my BookCard class
import {Button, Card, CardBody, CardHeader, CardImg, CardSubtitle, CardTitle} from "shards-react";
const BookCard=(props)=> {
function normalizeAuthors(arr) {
if(!arr)
{
arr=['no authors']
}
return arr;
}
return(
<Card style={{maxWidth:'300px'}}>
<CardHeader>
<CardTitle>{props.data.title}</CardTitle>
<CardSubtitle>{normalizeAuthors(props.data.authors)}</CardSubtitle>
</CardHeader>
<CardBody>
<CardImg src={props.data.imageLinks}/>
<Button outline >Learn More</Button>
</CardBody>
</Card>
)
}
export default BookCard
Upvotes: 0
Views: 1008
Reputation: 10652
You just have to let the parent know that the "Learn More" button is clicked.
For example:
function BooksDisplay(props) {
const [selectedbook, setSelectedBook] = React.useState();
const handleClick = (book) => {
// save this book in the state
setSelectedBook(book);
};
const books = props.books;
if (books.length === 0) {
return <div>{props.message}</div>;
} else {
return (
<div className="Books">
<div>{props.message}</div>
{books.map((book) => {
return (
<BookCard
clicked={() => handleClick(book)}
data={book.volumeInfo}
/>
);
})}
// In the `BookModal` component you can use the `bookData` prop.
<BookModal bookData={selectedbook} />
</div>
);
}
}
and in the BookCard
component:
const BookCard = (props) => {
function normalizeAuthors(arr) {
if (!arr) {
arr = ["no authors"];
}
return arr;
}
return (
<Card style={{ maxWidth: "300px" }}>
<CardHeader>
<CardTitle>{props.data.title}</CardTitle>
<CardSubtitle>{normalizeAuthors(props.data.authors)}</CardSubtitle>
</CardHeader>
<CardBody>
<CardImg src={props.data.imageLinks} />
<Button outline onClick={props.clicked}>
Learn More
</Button>
</CardBody>
</Card>
);
};
Upvotes: 1