Warning: Each Child in a list should have a unique "Key" prop.
I believe I am not the only one who's confused by the Key System as get started at React. This question focuses on inclusive situations on adding a key
prop.
Relevant reading I have done includes:
According to Adhithi Ravichandran, keys in iterations help React to identify which items have changed (added/removed/reordered).
1. For Component production, are keys supposed to be added in the iteration or component render method?
consider following movie component:
class Movie extends React.Component<any, any> {
render():JSX.Element{
let styles:React.CSSProperties = {
width: "300px",
height: "120px",
display: "flex",
justifyContent: "space-around",
alignItems: "center",
borderRadius: "20px",
filter: "drop-shadow(0px 1px 3px #6d6d6d)",
WebkitFilter: "drop-shadow(3px 3px 3px #6d6d6d)",
backgroundColor: '#'+Math.floor(Math.random()*16777215).toString(16),
fontSize: '2.5rem',
margin: '20px',
color: '#fff',
}
return (
<>
{/* add key to this div tag? */}
<div style={styles}>
{this.props.title}
</div>
</>
)
}
}
function test():JSX.Element{
return (
<>
{
['The Avengers', 'Ip Man', 'Now You See Me'].map(
// or add key to this Movie tag?
title=>(<Movie title={title} />)
)
}
</>
);
}
2. Is it appropriate to utilise a singleton id parser for generating key?
class Singleton {
private static _instance:Singleton = new Singleton();
public _ind:number = 0;
public _ids:Array<string> = ['r0'];
public _memory:boolean = false;
public _remember:Array<string|boolean|number> = [];
constructor(){
if(Singleton._instance){
return Singleton._instance;
}
Singleton._instance = this;
}
public new():string{
this._ind += 1;
this._ids.push(`r${this._ind}`);
let tar = this._ids[this._ids.length-2];
if(this._memory){this._remember.push(tar)}
return tar;
}
public placeholder(cos:string|boolean|number):void{
if(this._memory){this._remember.push(cos)}
}
public last():string{
return this._ids[this._ids.length-2];
}
public start_memorize():void{
this._memory = true;
}
public end_memorize():void{
this._memory = false;
}
public dump_memory():Array<string|boolean|number>{
let tar = this._remember.concat();
this._remember = [];
return tar;
}
public redeem(num:number){
for(let i=0; i<num; i++){
this._ids.pop();
this._ind -= 1;
}
}
}
export default Singleton;
Whereas Singleton.new()
is called for parsing a new key, take following as an example:
class Card extends React.Component<any, any>{
props:React.ComponentProps<any>;
singleton:Singleton;
constructor(props:any) {
super(props);
this.singleton = new Singleton();
}
render(){
return (
<>
<div key={this.singleton.new()}>
</div>
</>
)
}
}