Search code examples
javascriptreactjslistfirebasekey

How can I render a list by clicking a button in React?


I am working on a todo list using React and Firebase. I want to be able to click a button which will add a new todo, but render the todo as a list item. So far, I am mapping through the list with each todo, but when I add in the props, I am getting the error message Missing "key" prop for element in iterator, when I hover over the error in VSC. How can I add in a key prop, when using a button click to render a list? I included the code if it helps.

AddLink.js

import { useState, useEffect } from "react";
import classes from "./addlink.module.css";
import { AiOutlinePicture } from "react-icons/ai";
import { AiOutlineStar } from "react-icons/ai";
import { GoGraph } from "react-icons/go";
import { RiDeleteBin6Line } from "react-icons/ri";

import Modal from "../Modal/Modal";
import Backdrop from "../Backdrop/Backdrop";

import firebase from "firebase/app";
import initFirebase from "../../config";
import "firebase/firestore";
// import Links from "../Links/Links";

import Todo from "../Todo/Todo";

initFirebase();
const db = firebase.firestore();

function AddLink(props) {
  const [modalIsOpen, setModalIsOpen] = useState(false);
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState("");

  useEffect(() => {
    db.collection("links")
      .orderBy("timestamp", "desc")
      .onSnapshot((snapshot) => {
        setTodos(
          snapshot.docs.map((doc) => ({
            id: doc.id,
            todo: doc.data().todo,
          }))
        );
      });
  }, []);

  const addTodo = (event) => {
    event.preventDefault();

    console.log("clicked");

    db.collection("links").add({
      todo: input,
      timestamp: firebase.firestore.FieldValue.serverTimestamp(),
    });
    // empty input after the todo is successfully stored in firebase
    setInput("");
  };

  const deleteLink = () => {
    setModalIsOpen(true);
  };

  const closeModalHandler = () => {
    setModalIsOpen(false);
  };

  return (
    <div className={classes.addlink}>
      <form>
        <div className={classes.adminlink}>
          <input
            type="text"
            value={input}
            onChange={(event) => setInput(event.target.value)}
          />
          <button
            className={classes.adminbutton}
            type="submit"
            onClick={addTodo}
          >
            Add new link
          </button>
        </div>
        <div className={classes.adminsection}>
          <div className="link-cards">
            <h3>{props.text}</h3>
            <p>This is a new link</p>
            <div>
              <AiOutlinePicture />
              <AiOutlineStar />
              <GoGraph />
              <button onClick={deleteLink}>
                <RiDeleteBin6Line />
              </button>
            </div>
          </div>
        </div>
        {todos.map((todo) => (
          <Todo todo={todo} /> //This is where I am getting the error message
        ))}
        {modalIsOpen && (
          <Modal onCancel={closeModalHandler} onConfirm={closeModalHandler} />
        )}
        {modalIsOpen && <Backdrop onCancel={closeModalHandler} />}
      </form>
    </div>
  );
}

export default AddLink;

And then Todo.js

import React from "react";

function Todo(props) {
  return (
    <div>
      <li>{props.text}</li>
    </div>
  );
}

export default Todo;

Any help will be greatly appreciated.


Solution

  • There is an index as 2nd param of Array.map callback function

    You could use it as a key to your rendering, it's safe if you d don't do any re-ordering of your list.

    {
      todos.map((todo, index) => (
        <Todo key={index} todo={todo} />
      ));
    }
    

    If you want to have an actual key of your list, try out uuid lib, and generate a key as your adding a new todo item.

    Something like this:

    import { v4 as uuidv4 } from 'uuid';
    
    const addTodo = event => {
      event.preventDefault();
    
      console.log("clicked");
    
      db.collection("links").add({
        id: uuidv4(),  //<-- Add random unique key to your todo item
        todo: input,
        timestamp: firebase.firestore.FieldValue.serverTimestamp()
      });
      setInput("");
    };