2
votes

This is only my second question here, so sorry if it's in the wrong place or has the wrong tags or anything.

import React from 'react';
import { connect } from 'react-redux';
import { getUnits } from '../reducers/units';
import { Menu, Container, Grid, Header, Form } from 'semantic-ui-react';

class Units extends React.Component {

  componentDidUpdate(prevProps) {
    const { dispatch, course } = this.props
    if (prevProps.course.id !== course.id)
      dispatch(getUnits(course.id))
  }

  units = () => {
    return this.props.units.map( unit => 
      <ul>
        <li key={unit.id}> {unit.name}</li>
        <button>Edit Module Name</button> 
        <button>Delete Module</button> 
      </ul> 
    )
  }

  render() {
    return (
      <Container>
        <Header as="h3" textAlign="center">Modules</Header>
        { this.units() }
      </Container>
    )
  }
}
const mapStateToProps = (state) => {
  return { units: state.units, course: state.course }
}

export default connect(mapStateToProps)(Units);

I'm getting the error in the title of this question even though I have keys in the li elements and they are unique. I can see that they're different in the redux dev tools state, but for some reason I still get that error. I have looked at other similar errors here on stackoverflow but none of those seemed to solve this specific problem.

2
Possible duplicate of React unique "key" errorAlex Young

2 Answers

7
votes

The answer @NorianNyx is good, basically you need to add an unique key to each component. However adding a index is not a good practice as this will not represent the item every single time. If you delete or add a new item to the list the index will change.

From React:

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys

So the updated solution to this will be:

return this.props.units.map((unit) => (
<ul key={unit.id}>
    <li> {unit.name}</li>
    <button>Edit Module Name</button> 
    <button>Delete Module</button> 
</ul>

));

In this way your item always will have an unique id

3
votes

Your <ul> component needs a key prop.

Just change it to:

 return this.props.units.map((unit, i) => (
    <ul key={i}>
        <li> {unit.name}</li>
        <button>Edit Module Name</button> 
        <button>Delete Module</button> 
    </ul>
 ));