Home > Mobile >  I can't call a function that I've assigned to an element in React
I can't call a function that I've assigned to an element in React

Time:12-06

App.jsx `

import React, { useState } from "react";
import ToDoItem from "./ToDoItem";

function App() {
  const [inputText, setInputText] = useState("");
  const [items, setItems] = useState([]);

  function handleChange(event) {
    const newValue = event.target.value;
    setInputText(newValue);
  }

  function addItem() {
    setItems((prevItems) => {
      return [...prevItems, inputText];
    });
    setInputText("");
  }

  function deleteItem() {
    console.log("item called delete.");
  }

  return (
    <div className="container">
      <div className="heading">
        <h1>To-Do List</h1>
      </div>
      <div className="form">
        <input onChange={handleChange} type="text" value={inputText} />
        <button onClick={addItem}>
          <span>Add</span>
        </button>
      </div>
      <div>
        <ul>
          {items.map((todoItem) => (
            <ToDoItem
              key={items.toString()}
              text={todoItem}
              onChecked={deleteItem}
            />
          ))}
        </ul>
      </div>
    </div>
  );
}

export default App;

`

ToDoItem.jsx `

import React from "react";

function ToDoItem(props) {
  return <li onClick={props.onCheked}>{props.text}</li>;
}

export default ToDoItem;

`

①I'm trying to call the 'deleteItem' function when the elements are clicked. I'm checking this with a console.log inside the function. However it never works when I click on the element.

②When I clicked on the element, there were a warning appearing in the console: Warning: Each child in a list should have a unique "key" prop. So I checked in the React document and added key={items.toString()} . But When I added the second item in the list, there appeared another warning: Warning: Encountered two children with the same key

I wonder how I can solve these two problems. Can anyone help?

CodePudding user response:

key prop in react element: It help internal react processing that enable reuse react element instance created before. In your example, you can use index of item or id of item for key value. Ex: or

CodePudding user response:

① Do you have some errors in the console?

② When you call key={items.toString()} the key will have the same value for each child because you refer to the item list. Try to add an id in ToDoItem and use it for the key key={todoItem.id} or more easily key={todoItem.toString()} (but with the last one you can't have two items with the same text)

  • Related