Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Each child in a list should have a unique "key" prop. How is it resolve

I don’t understand what is problem in my todo list make.

import React, { useState } from 'react';
import Task from './component/Task'

function App() {

    const [task, setTask] = useState();
    const [taskList, setTaskList] = useState([]);

    function AddTask() {
        setTaskList([...taskList, { task: task }]);
        setTask('');
    }
    return (
        <div>

            <h1>List</h1>
            <input type='text' placeholder='fill your tast' onChange={(e) => { setTask(e.target.value) }} />
            <button onClick={AddTask}>Add</button>
            {
                taskList.map((task, i) => {
                    return (
                        <div>
                            <Task key={i} task={task.task} />
                        </div>
                    )
                })
            }
        </div>
    )

}

export default App;




another component

import React from 'react';

function Task(task) {
    return (
        <div>
            {task.item}
        </div>
    )
}

export default Task;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The key prop is required when you are mapping an array as JSX element.
Notice how i used key in div and not in Task, this means you’ll need to use key property in the higher level elemen.

const [task, setTask] = useState();
const [taskList, setTaskList] = useState([]);

function AddTask() {
    setTaskList([...taskList, { task: task }]);
    setTask('');
}
return (
    <div>

        <h1>List</h1>
        <input type='text' placeholder='fill your tast' onChange={(e) => { setTask(e.target.value) }} />
        <button onClick={AddTask}>Add</button>
        {
            taskList.map((task, i) => {
                return (
                    <div key={`${i}`}>
                        <Task task={task.task} />
                    </div>
                )
            })
        }
    </div>
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading