Sign in
Log inSign up

React question. Return only one element but gets undefined for some reason.

Default profile photo
Anonymous
·Sep 27, 2018

Take notice on lines under this.renderSlides():

-- My objective is for this.renderSlides() to return only 1 <li> at a time.

-- The hurdle.... if this.state.slideIndex is properly updated(proven via console.log()) and slides is an array, then why does it keep returning undefined at return slides[i]????

import _ from 'lodash'
import React, { Component } from 'react'

import './Carousel.css'

class Carousel extends Component {
 state = {
  slideContents: [],
  slideIndex: 0
 }

 onNextSlide = () => {
  const c = `${Date.now()}`
  this.setState({ slideIndex: this.state.slideIndex + 1 })
  this.setState({ slideContents: [ ...this.state.slideContents,  c ]});
 }

 onPreviousSlide(slide) {
  this.setState({ slideContents: _.without(this.state.slideContents, slide) });
 }

 renderSlides() {
  const slides = this.state.slideContents.map((item, index) => {
   return (
    <li key={item} className="animated fadeIn">{ item }</li>
   )
  })
  const i = this.state.slideIndex
  return slides[i]
 }

 render() {
  return (
   <div>
     <h1>carousel works!</h1>
     <button onClick={this.onNextSlide}>next</button>
     <ul>{this.renderSlides()}</ul>
   </div>
  )
 }
}

export default Carousel

--