Home > Software engineering >  How to update the parent / list component from the child / detail component in ReactJS?
How to update the parent / list component from the child / detail component in ReactJS?

Time:05-04

I am beginner and practicing on Library Management System in react. So I have components named BookDetails.js, BookList.js. BookDetails contains the form for entering Title and Description. So How can I pass the data entered from BookDetails to BookList and to dispaly from App.

import React, { useState } from 'react'
import BookList from './BookList'
const BookDetails = (props) => {
const [bookdetails, setbookDetails] = useState('')
const [desc, setDesc] = useState('')

    const titleChangehandler = (e) => {
        setbookDetails(e.target.value)

    }
    const descriptionChangehandler = (e) => {
        setDesc(e.target.value)

    }
    const submitHandler = (e) => {
        e.preventDefault()

        return (
            <div className='bookdetails'>
                <form className='form_bookdetails' onSubmit={submitHandler}>
                    <div>
                        <label>Enter Title:</label>
                        <input type='text' value={bookdetails} onChange={titleChangehandler}></input>
                    </div>
                    <div>
                        <label>Enter Description:</label>
                        <input type='text' value={desc} onChange={descriptionChangehandler}></input>
                    </div>
                    <div>
                        <button type='submit'>Add Details</button>
                    </div>

                </form>
            </div>
        )
    }
}

export default BookDetails

BookList.js

import React from 'react'
import './BookList.css'
import BookDetails from './BookDetails'

const BookList = () => {


  return (
    <div className="booklist">
      <header>BookList</header>
      <BookDetails  />
    </div>

  )
}

export default BookList


CodePudding user response:

You need to use props. BookList state will have an update function that it will pass to the BookDetail via props. Example (CodeSandbox) with Todo with title & description.

BookDetail will invoke this method on every save which then would update the original list.

TodoList.js

export default function TodoList() {
  const [todo, setTodo] = React.useState(null);
  const [todoList, setTodoList] = React.useState([]);

  React.useEffect(() => {
    getTodos();
  }, []);

  function getTodos() {
    console.log("===> fetch all todos!!");
    fetchTodos().then((todos) => {
      setTodoList(todos);
    });
  }

  function editTodo(todo) {
    console.log("===> set todo => ", todo);
    setTodo(todo);
  }

  function handleUpdate(updatedTodo) {
    // update Todo
    const updatedTodos = todoList.map((el) =>
      el.id === updatedTodo.id ? updatedTodo : el
    );
    setTodoList(updatedTodos);
    setTodo(null);
  }

  return (
    <div>
      <ul>
        {todoList.map((item) => (
          <li key={item.id}>
            {item.title}, {item.description}
            <button onClick={() => editTodo(item)}>edit</button>
          </li>
        ))}
      </ul>
      {todo && <TodoDetail todo={todo} updateTodo={handleUpdate} />}
    </div>
  );
}

TodoDetail.js

import React from "react";

export default function TodoDetail(props) {
  const [todo, setTodo] = React.useState(props.todo);
  console.log("todo =>", todo);
  function handleChange(key, value) {
    console.log("===> todo changed!");
    setTodo({
      ...todo,
      [key]: value
    });
  }

  function handleSubmit() {
    // api PUT on todo
    console.log("===> todo edit submit!!");
    props.updateTodo(todo);
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label htmlFor="title">
          <input
            value={todo.title}
            onChange={(e) => handleChange("title", e.target.value)}
          />
          <input
            value={todo.description}
            onChange={(e) => handleChange("description", e.target.value)}
          />
        </label>
        <button type="submit">submit</button>
      </form>
    </div>
  );
}

CodePudding user response:

You can store the list of books in your BookList component like

const [bookList, setBookList] = useState([])

This way your BookList component has access to the books. You can then create a function to add books to the list

  function addBook(book) {
     setBookList([...bookList, book])
  } 

Then pass the addBook() function to the BookDetails component to use it on submit.

<BookDetails addBook={addBook}

Now BookDetails can access the function as a prop

props.addBook("pass new book here")
  • Related