How to update a list of books from another component that is a form?

Viewed 198

Hi every one I'm kinda new to react and I'm trying a tutorial about some kind of book library. which I have a AddNewBook Component which is a form like this:

function AddNewBook(){
  const [name, setName] = useState("");
 
  const handleChange = e => setName(e.target.value);
  return (
    <input name="book-name" onChange={handleChange} />
  )
}

and I Have another component which I show the books like this:

function BooksList(){
  const [books, setBooks] = useState([]);

  return (books?.map((book, i) => <div key={i}>{book.name}</div>))
}

I have my App.js Component like this:

function App(){

 return (
  <div> 
   <AddNewBook />
   <BooksList />
  </div>
 );
}

my question is how can I update the booksList in a best practice manner. There is a possibility that I might have extend the components later and have more components around this.

1 Answers

You should lift the bookList state up to the parent component of both AddNewBook and BooksList. And then pass the necessary things as props to the components.

function App(){
    const [books, setBooks] = useState([]);
    
    function addBook(bookName) {
        setBooks([...books, { name: bookName }]);
    }

    return (
        <div>
            <AddNewBook onAddBook={addBook} />
            <BooksList books={books} />
        </div>
    );
}


function BooksList({ books }){
    return (books?.map((book, i) => <div key={i}>{book.name}</div>))
}

function AddNewBook({ onAddBook }){
    const [name, setName] = useState("");

    const handleChange = e => setName(e.target.value);
    return (
        <div>
            <input name="book-name" value={name} onChange={handleChange} />
            <button onClick={() => onAddBook(name)}>Add Book</button>
        </div>
    )
}
Related