javascript - Showing N list items in React component without JQuery -


after lots of reading on so, i've come conclusion using jquery inside react component part, bad practice. how accomplish following, being react-friendly possible...

lets have list in component:

let mylist = [     {title: 'list item 1'},     {title: 'list item 2'},     {title: 'list item 3'},     {title: 'list item 4'},     {title: 'list item 5'},     {title: 'list item 6'} ] 

i want show first 3 items, unless show all clicked.

and render() looks like:

render () {      return (       <div>       mylist.map(function(item, i) {           <a>{item.title}</a>       }       <a>show all</a>       </div>    ) } 

i know how how in jquery, i'm wondering solution using react best practices.

i write function encapsulates logic of show. then, you'll need use state capture whether show clicked or not, can differentiate when want show first 3 , when want show all. key return array of jsx want rendered:

renderitems() {   const itemlist = [];   // can more succinct here - demo purposes   (let = 0; < mylist.length; i++) {     if (this.state.showall !== true && === 3) {       break;     }     itemlist.push(<a>{ mylist[i].title }</a>);   }   return itemlist; }  render() {   return (     <div>       { this.renderitems() }     </div>   ); } 

you'll need add handler when clicks "show all" set state:

<a onclick={ this.showall }>show all</a> 

if reference instance method this, make sure bind in constructor "this":

constructor() {   this.showall = this.showall.bind(this);   this.state = {     showall = false;   }; } showall(e) {   e.preventdefault();   this.setstate({ showall: true }); } 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -