Home > database >  How to update and display the parent / list component from the child / detail component in ReactJS?
How to update and display the parent / list component from the child / detail component in ReactJS?

Time:05-08

0

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. On submiting form the I got a warning "Warning: Each child in a list should have a unique "key" prop". from Display function of bookdetails. So what should I add to display entered form data. Here is my code as: BookDetails.js

import React, { useState } from 'react' import './BookDetails.css'

    const [bookTitle, setbookTitle] = useState('');
    const [desc, setDesc] = useState('');

    const titleChangehandler = (e) => {
        setbookTitle(e.target.value);

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

    }
    const submitHandler = (e) => {
        e.preventDefault();
        props.addBook();
    }


    return (
        <div className='bookdetails'>
            <form className='form_bookdetails' onSubmit={submitHandler}>
                <div>
                    <label>Enter Title:</label>
                    <input type='text' value={bookTitle} 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, { useState } from 'react'
import './BookList.css'
import BookDetails from './BookDetails'

const BookList = () => {
  const [bookList, setBookList] = useState([])

  const addBook = (book) => {
    setBookList([...bookList, book])

  }
  const Display=()=>{
    return (
      <ul>
      {bookList.map((list) => (
          <li key={list}>{list}</li>
        ))}
      </ul>
    );
  }


  return (
    <>
      <div className="booklist">
        <header>BookList</header>
        <BookDetails addBook={addBook}/>
        <Display/>
      </div>
    </>

  )
}

export default BookList

CodePudding user response:

You need to add a unique key for each child so react can differ between different children. here is what the simplest approach would be:

const Display=()=>{
    return (
      <ul>
      {bookList.map((list, index) => (
          <li key={index}>{list}</li>
        ))}
      </ul>
    );
  }

remember that it is not a best practice to use index as a key, especially when you're list items changes frequently you should choose more specific key for the item, but in this case it's Ok

CodePudding user response:

You are forgot use keys one list items , keys

const Display=()=>{
    return (
      <ul>
      {bookList.map((list, index) => (
          <li key={somethingUnique}>{list}</li>
        ))}
      </ul>
    );
  }

if you not have something unique , you can use this library uuid

The best practices

CodePudding user response:

You need first to make sure you pass the book as an argument when you call the function props.addBook() from BookDetails component:

const submitHandler = (e) => {
 e.preventDefault();
 props.addBook({
  title: bookTitle,
  description: desc
 });
}

Then you should also use a string unique key for each li element you are rendering. If you know that each book needs to have a different title than you can use a title as unique key, otherwise I suggest you to create a unique id for each book (that you need to store in the book object). For the purpose of this exercise I will just suppose that each title is unique:

{bookList.map(({title, description}) => (
 <li key={title}>{`${title}, ${description}`}</li> // make sure to not render the entire object list because that is not allowed
))}

Here you can find some docs from React that suggests to use strings as unique key and not the index of the array: https://reactjs.org/docs/lists-and-keys.html#keys

  • Related