Search code examples
reactjsuuid

I have installed uuid, but it does not work


I'm using uuid for providing unique Ids, but I still get this warning:

Each child in a list should have a unique "key" prop.

function NavBar () {
return(
    <ul className='nav justify-content-center'>
        <Link /*to={item.ref}*/ className="nav-link">
            <li className="nav-item" key={uuid()}> Home </li>
        </Link>
        {
            navItems?.map((item) => {
                return(
                    <>
                    <span className="listStyle"></span>
                    <Link to={item.ref} className="nav-link">
                        <li className="nav-item" key={uuid()}> {item.name} </li>
                    </Link>
                    </>
                )
            })
        }
    </ul>
);
}

Solution

  • Few issues here.

    Firstly it should be attached to the outermost element. Secondly the point of a key is to be stable across renders - this tells React not to remount / recreate the component and instead just to re-render it. (Big performance improvement). You should use something static, such as item.ref. This is because otherwise (as we're regenerating the items based on the list on every render) React has no way to track them every time it updates the component, this helps resolve that.

    For example:

    function NavBar () {
    return(
        <ul className='nav justify-content-center'>
            <Link /*to={item.ref}*/ className="nav-link">
                <li className="nav-item" key={uuid()}> Home </li>
            </Link>
            {
                navItems?.map((item) => {
                    return(
                        <span key={item.ref}>
                            <span className="listStyle"></span>
                            <Link to={item.ref} className="nav-link">
                                 <li className="nav-item"> {item.name} </li>
                            </Link>
                        </span>
                    )
                })
            }
        </ul>
    );
    }