3

I get the very common Warning: Each child in an array or iterator should have a unique "key" prop. This is usually very easy to resolve but in this case its just impossible to me to figure out where the issue is created.

My stack trace:

 in hoc (created by Connect(hoc))
    in Connect(hoc) (at withTranslation.js:7)
    in hoc (at ConnectedProtectedRoutes.js:26)
    in Route (at ConnectedProtectedRoutes.js:44)
    in ProtectedRoutes (created by Connect(ProtectedRoutes))

withTranslation Component

export function withTranslation(CMP) {
    var hoc = class extends React.Component {
        render() {
            return <CMP {...this.props} translate={translate} />
        }
    };
    return hoc;
}

ConnectedProtectedRoutes

const ProtectedRoutes = ({ token, authority, location }) => {
    var a = [
        createRouteWithRequirements(<Login key="1"/>, "/", [], { token, authority }, true),
        createRouteWithRequirements(<Login key="2"/>, "/login", [], { token, authority }),
        createRouteWithRequirements(<Register key="3"/>, "/register", [], { token, authority })
    ]

    return a
};

const createRouteWithRequirements = (component, url, requirements, injections, exact) => {
    return (
        <Route //this is -> in Route (at ConnectedProtectedRoutes.js:44)
            exact={!!exact}
            key={url}
            path={url}
            render={() => {
                if (requirements.includes("token") && !injections.token) {
                    return <Redirect to="/login" />
                }

                return component;
            }}
        />
    );
};

And the stack goes on but im guessing the issue is somewhere in there. Any clues?

Return-1
  • 2,171
  • 2
  • 20
  • 53
  • Are you rendering anything else in the parent component that might have the same keys (eg `key="1"`)? If you have two separate lists mounted at the same time and some list elements have same key, then the warning would show up. – samzmann Feb 24 '20 at 13:22

1 Answers1

-1

In your ProtectedRoutes component you are defining an array and using it somewhere else. Hence, each array needs a key, this is why you are getting warning. So, handle the key for this array.

devserkan
  • 15,490
  • 4
  • 29
  • 45
  • lemme try, i was confident that when defining an array like that the index was used as a key. brb – Return-1 Apr 03 '18 at 13:17
  • still getting the error, changed as shown in EDIT,pretty sure i tried that in the past as well. in very fact, i can see i pass the entire url as a key ( forgot i even did that as an attempt to avoid the issue ) – Return-1 Apr 03 '18 at 13:18
  • I'm not a pro but I'm pretty sure keys are not handling automatically for arrays :) I was sure that will solve the problem. I can't see anything causes that error in your code now. – devserkan Apr 03 '18 at 13:22
  • i know right? this has been popping up in my console for too long a time now, you can imagine the OCD triggering – Return-1 Apr 03 '18 at 13:24