In React component I have array of books, on click of Hide Books I set array of data to empty so nothing is displayed on page the change Button text to Show Books
What I am trying to achieve is When click on button with text Show Books I want to display data by setting setBooksData(bookData)
function BookList() {
const [booksData, setBooksData] = useState(books);
const clearBooks = () => {
setBooksData([]);
};
return (
<section className="booklist">
{booksData.map((book, index) => {
return <Book key={index} {...book}></Book>;
})}
<button onClick={clearBooks}>
{booksData.length === 0 ? "Show Books" : "Hide Books"}
</button>
</section>
);
}
CodePudding user response:
We can use a another state to hide and show the book list. In your code you have made booklist as empty, so that when you click on the show book, booklist will be empty.
Now here i have used another state to hide and show the books. to show the book i have added two condition to check whether the book array has data and whether in show state.
function BookList() {
const [booksData, setBooksData] = useState(books);
const [hideBook,setHidden]=useState(false);
const clearBooks = () => {
setHidden(!hideBook)
};
return (
<section className="booklist">
{!hideBook && booksData.length >0 &&
booksData.map((book, index) => {
return <Book key={index} {...book}></Book>;
})
}
<button onClick={clearBooks}>
{hideBook ? "Show Books" : "Hide Books"}
</button>
</section>
);
}
CodePudding user response:
Since both buttons have different functionality, you can separate them, and assign each its own handler functions
function BookList() {
const [booksData, setBooksData] = useState(books);
const clearBooks = () => {
setBooksData([]);
};
const handleShowBook = () => {
setBooksData(books);
}
return (
<section className="booklist">
{booksData.map((book, index) => {
return <Book key={index} {...book}></Book>;
})}
{
booksData.length === 0
?
(<button onClick={handleShowBook}>
Show Books
</button>)
:
(<button onClick={clearBooks}>
Hide Books
</button>)
}
</section>
);
}
