Map Function for Dynamic Rendering of Arrays
render ( ) {
let cartoons = [ "Pika" , "Squi" , "Bulb" , "Char" ] ;
return (
< ul >
{ cartoons. map ( name => < li key = { name} > { name} < / l i > ) }
< / ul >
) ;
}
ES6 spread functions can be used to send a whole list of parameters in an object by using Object.keys().
render ( ) {
let cartoons = {
"Pika" : {
type : "Electric" ,
level : 10
} ,
"Squi" : {
type : "Water" ,
level : 10
} ,
"Bulb" : {
type : "Grass" ,
level : 10
} ,
"Char" : {
type : "Fire" ,
level : 10
}
} ;
return (
< ul >
{ Object. keys ( cartoons ) . map ( name => < Cartoons key = { name } { ... cartoon [ name ] } / > ) }
< / ul >
) ;
}
class Item extends Component {
state = {
listitems : [
{
id : 0 ,
context : "Primary" ,
modifier : "list-group-item list-group-item-primary"
} ,
{
id : 1 ,
context : "Secondary" ,
modifier : "list-group-item list-group-item-secondary"
} ,
{
id : 2 ,
context : "Success" ,
modifier : "list-group-item list-group-item-success"
} ,
{
id : 3 ,
context : "Danger" ,
modifier : "list-group-item list-group-item-danger"
} ,
{
id : 4 ,
context : "Warning" ,
modifier : "list-group-item list-group-item-warning"
}
]
} ;
render ( ) {
return (
< React . Fragment >
< ul className = "list-group" >
{ this. state . listitems . map ( listitem => (
< li key = { listitem . id } className = { listitem . modifier } >
{ listitem . context }
< / l i >
) ) }
< / u l >
< / R e a c t .F r a g m e n t >
) ;
}
}
Dynamic Rendering with && and the Ternary Operator
class FilterResult extends Component {
render ( ) {
let { filterResults } = this . props ;
return (
< section className = "search-results" >
{ filterResults. length > 0 &&
filterResults . map ( index => < Result key = { index } { ... results [ index ] / > )
}
{ filterResults. length === 0 &&
< div className = "no-results" > No results < / d i v >
}
< / section >
) ;
}
}
// Better
class FilterResult extends Component {
render ( ) {
let { filterResults } = this . props ;
return (
< section className = "search-result" >
{ filterResults. length > 0
? filterResults . map ( index => < Result key = { index } { ... filterResults [ index ] / > )
: < div className = "no-result" > No results < / d i v >
}
< / section >
) ;
}
}