React/Typescript location.key is not unique

Viewed 39

When I create CRUD forms in React/Typescript they merge with each-other because the keys of both are the same.

 return (
    <div className="App d-flex flex-column min-vh-100">
      <Route exact path='/' component={HomePage} />
      <Route
        path={'/(.+)'}
        render={() => (
          <>
            <NavBar />
            <Container style={{ marginTop: '7em' }}>
              <Route exact path='/subject' component={SubjectDashboard} />
              <Route key={location.key} path={['/createSubject', '/manage/:id']} component={CountryForm} />
              <Route exact path='/departments' component={DepartmentDashboard} />
              <Route key={location.key} path={['/createDepartment', '/manages/:id']} component={DepartmentForm} />
            </Container>
          </>
        )}
      />

I tried location.pathname but still the same problem. this only works if one of them is location.key and the other location.pathname , but when I add the third CRUD form it breaks agian.

1 Answers

If you've read the React Documentation regarding keys, you'd see that the key property is primarily used in scenarios where a list or collection of data need to be rendered and its used to determine which component has changed in that list.

So a key needs to be unique to that specific piece of data, if in the case of sibling components - which is what you have.

But <Route /> component doesn't need a key to work. And in your case, since you're not rendering a list, then you don't really need it. You should be able to remove them and it'll work fine.

So these are my recommendations:

  • Remove the key prop from both of those elements
  • Or for whatever reason you need them in, use different values for them. Maybe append -subject and -department to location.key so key={location.key + '-subject'}
Related