CodesJava

Easy learning with example program codes

Map in ReactJS

React Map
A map is the standard JavaScript function, and also a type of data collection. Here, data is stored in the form of pairs. Each value stored in the map is mapped to a unique key. Thus a duplicate pair is not allowed in a map thus it offers a fast searching of data.

Example:

var num = [10, 20, 30, 40, 50];   
const X = num.map((number)=>{   
return (number + 50);   
});   
console.log(X);

Explanation:
Here an array of numbers is passed to a map. A value of 50 is then added to each of the number, which is then logged.

Uses of map() method in ReactJS:

To traverse the list elements Example:

import React from 'react';   
import ReactDOM from 'react-dom';   
function example(props) {  
const names = props.names;  
const nameList = names.map((name) =>  
<li>{name}</li>  
);  
return (  
<div>  
<h2>Name List:</h2>  
<ul>{nameList}</ul>  
</div>  
);  
}  
const names = ['Ali', 'Bond', 'Catherine', 'David', 'Don'];   
ReactDOM.render(  
<example names={names} />,  
document.getElementById('app')  
);  
export default App;

Output:

To traverse the list element with keys Example:

import React from 'react';   
import ReactDOM from 'react-dom';   
function example(props) {  
return <li>{props.value}</li>;  
}    
function NumList(props) {  
const nums = props.nums;  
const numList = nums.map((num) =>  
<example key={num.toString()}  
value={num} />  
);  
return (  
<div>  
<h2>Number List:</h2>  
<ul> {numList} </ul>  
</div>  
);  
}  
const nums = [10, 20, 30, 40, 50];  
ReactDOM.render(  
<NumList nums={nums} />,  
document.getElementById('app')  
);  
export default App;

Output:

Please follow and like us:
error









Copyright © 2019 CodesJava DMCA.com Protection Status