简体   繁体   中英

React - Each child in a list should have a unique “key” prop

In My react component, My UI loads perfectly but there is console error which i wanted to fix error says - ' Each child in a list should have a unique "key" prop ' for below code. Guide me how I can pass keys to detailsContent

render() {
    const header = (
        <div className={css.deviceDetailsBody}>
            <div className="sidebar__header">
                <div className="sidebar__title">
                    <div>
                        {hostname}
                        {this._renderCloser()}
                        <div className={"sidebar__subtitle"}>
                            <div className="toolsBar">
                                <div className="toolsBarlet">
                                    <div className="toolsItemNarrow">{deviceTypeView}</div>
                                    {complianceStatusView}
                                    <div className="toolsItemNarrow">{managementIpAddress}</div>
                                    {deviceUpTime}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
    const horizontalLine = <div className="sidebar__horiz_line" />;
    const body = (
        <div className="body">
            {tabs}
            {tools}
        </div>
    );

    const detailsContent = [header, horizontalLine, body].map(
        currentComponent => currentComponent
    );

    return (
        <div>
            {sideBarShow && (
                <Sidebar {...sidebarProps}>
                    <div>{detailsContent}</div>
                </Sidebar>
            )}
        </div>
    );
}

Added the header, body code for more clarity.

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

If using Components and not plain jsx elements, simply add a key prop to the currentComponent jsx. Note for simplicity I just used index as key.

const detailsContent = [header, horizontalLine, body].map(
  (CurrentComponent, index) => (<CurrentComponent key={index} />)
);

See CodeSandbox

Using elements, please refer to the accepted answer .

You can use React.cloneElement to add keys

const detailsContent = [header, line, body].map(
  (element, index) => React.cloneElement(element, {key: index})
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM