React Keys
A “key” is a special string attribute you need
to include when creating lists of elements in React.
Keys are used in react to identify which items
in the list are changed, updated (or) deleted. In other words we can say that
keys are used to give an identity to the elements in the lists.
It also helps to determine which components in a
collection needs to be re-rendered instead of re-rendering the entire set of
components every time.
Advantage:
* Time and Memory will save.
Use:
In
shopping websites like amazon, flipkart websites filter option.
Index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import './myfile.scss';
import App from './App';
import reportWebVitals from './reportWebVitals';
import styles from './demo.module.css';
const root = ReactDOM.createRoot(
document.getElementById('root')
);
function Menubar(props)
{
const content=props.data.map((show)=>
<div key={show.id}>
<h3>{show.id} : {show.title} : {show.content}</h3>
</div>
);
return(
<div>{content}</div>
);
}
const myvalue=[
{id:1,title:'First',content:'Hello World'},
{id:2,title:'Second',content:'Welcome to
the World'}
];
var mystyle={color:'green',textAlign:'center'}
const element =<Menubar data={myvalue}/>
root.render(element);
Output
React key using data Type
Index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import './myfile.scss';
import App from './App';
import reportWebVitals from './reportWebVitals';
import styles from './demo.module.css';
const root = ReactDOM.createRoot(
document.getElementById('root')
);
function Listkey(props)
{
const item=props.items;
const key=props.keys;
return(
<li>{key}{item}</li>
);
}
function MyList(props){
const listItem=props.myvalue.map((listvalue,index)=>
<Listkey keys={index} item={listvalue}/>
);
return(
<div>
<h2>Correct key Usage Example</h2>
<ul>{listItem}</ul>
</div>
);
}
const mydata=[200,1000,5000,300];
var mystyle={color:'green',textAlign:'center'}
const element =<MyList myvalue={mydata}/>
root.render(element);
Output
No comments:
Post a Comment