skip to Main Content

Getting this error
"Each child should have a unique key prop"

My code is as follows

import React, { useState } from 'react'

export default function Folder({ datas }) {
  const [toggleFolder, setToggleFolder] = useState(false);

  return (
    <>

      <div
        onClick={() => setToggleFolder(prev => !prev)}
        className='cursor-pointer'>📁 {datas.folder}</div>
     
     
      <div
        key={datas.id}
        style={{ display: toggleFolder ? "block" : "none" }}
        className='pl-[20px]'
      >
        {
          datas.children && datas.children.length > 0 ?
            datas.children.map((key, index) => {
              return <Folder datas={key} />
            })
            : <p className='opacity-70'>empty</p>
        }
      </div>
    </>
  )
}

2

Answers


  1. import React, { useState } from 'react';
    
    export default function Folder({ datas }) {
      const [toggleFolder, setToggleFolder] = useState(false);
    
      return (
        <>
          <div
            onClick={() => setToggleFolder(prev => !prev)}
            className='cursor-pointer'
          >
            📁 {datas.folder}
          </div>
    
          <div
            key={datas.id}
            style={{ display: toggleFolder ? "block" : "none" }}
            className='pl-[20px]'
          >
            {datas.children && datas.children.length > 0 ? (
              datas.children.map(child => (
                <Folder key={child.id} datas={child} />
              ))
            ) : (
              <p className='opacity-70'>empty</p>
            )}
          </div>
        </>
      );
    }
    

    Even after it remains try adding an index

    (
     datas.children.map(child,index) => (
        <Folder key={index} datas={child} />
    ))
    
    Login or Signup to reply.
  2. You should add this key=index.

    <Folder key={index} data={key}/>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search