Reputation: 53
I am trying to assign index to key of dynamic list component but it gives warning of duplicate keys. Here is the code below
function App() {
const [userInput, setUserInput] = useState('');
let calcLengthHandler = (event)=>{
setUserInput(event.target.value);
}
let charArr = [...userInput.split('')];
let charCmp = ( <div>
{
charArr.map((character,index)=>{
return (
<CharComponent onClick={deleteCharCmp} char={character} key='index'></CharComponent>
)
})
}
</div>)
return (
<div className="App">
<div className='container'>
<h1 className='container-output'>Dynamic List</h1>
<input type='text' className='user-input' onChange={calcLengthHandler} value={userInput} placeholder='Enter user input'></input>
<p className='container-output inline'>Length of user input: {userInput.length}</p>
<ValidationComponent length={userInput.length}></ValidationComponent>
{charCmp}
</div>
</div>
);
}
Every time a user enters some string, I am trying to create a component with each character. I have further functionality to achieve which I have not included. On adding debugger just before .map function, I see its called twice which may be causing the issue. I guess 1. when the component is initialized and 2. when I call {charCmp}. How can I resolve duplicate keys problem here?
Upvotes: 1
Views: 171
Reputation: 2711
This sets the key
attribute to the string 'index'
:
key='index'
This sets the key
attribute to the value of the index
variable:
key={index}
Upvotes: 2