Berikut adalah contoh looping pada ReactJS :
Looping
1. Looping data dengan Map
import React, {Component} from 'react'
class loopMap extends Component{
state ={ data:[1,2,3,4,5,6,7,8,9,10] }
render(){
const result = this.state.data.map((value, index) => {
return(<li key={index}>{value}</li>)
})
return(
<div>
<h1>Looping dengan Map </h1>
<ul>
{result}
</ul>
</div>
)
}
}
export default loopMap
2. Looping array multidimensi
import React from 'react';
const pelajars = [
{
'id': 1,
'name': 'Pelajar 1',
'email': 'pelajar1@yahoo.com'
},
{
'id': 2,
'name': 'Pelajar 2',
'email': 'pelajar2@gmail.com'
},
{
'id': 2,
'name': 'Pelajar 3',
'email': 'pelajar3@hotmail.com'
},
];
function loopMultidimensi() {
return (
<div>
<table className="table table-bordered">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
{pelajars.map((pelajar, index) => (
<tr data-index={index}>
<td>{pelajar.id}</td>
<td>{pelajar.name}</td>
<td>{pelajar.email}</td>
</tr>
))}
</table>
</div>
);
}
export default loopMultidimensi;
Condition
1 . Conditional Rendering di Luar JSX
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
2. Inline if
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Email </h1>
{unreadMessages.length > 0 &&
<h2>
Anda punya email : {unreadMessages.length} unread messages.
</h2>
}
</div>
);
}
3. Inline If-Else
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
User login <b>{isLoggedIn ? 'Sekarang' : 'bukan'}</b> logged in.
</div>
);
}