0

I'd like to do animated menu like on this site (I'm thinking now about the images below the navbar that move by themselves):

I've got a component with 3 states and each state indicates which image with link should be displayed. I believe I should use setTimeout to change the state of the component. I tried to do this in componentDidMount/componentWillMount methods but I receive the error:

TypeError: Cannot read property 'why' of undefined

That indicates, as far as I understand, that the state is not set? What am I doing wrong?

export default class Menu extends Component {
  constructor(props) {
    super(props)
    this.state = {
      why: true,
      shop: false,
      workshop: false
    }
  }

  componentWillMount() {
    setInterval(function(){
      if (this.state.why) {
        this.setState({why: false, shop: true, workshop: false})
      }
      else if (this.state.shop) {
        this.setState({why: false, shop: false, workshop: true})
      }
      else if (this.state.workshop) {
        this.setState({why: true, shop: false, workshop: false})
      }
    }, 3000);
  }

  render() {
    return (
      <div>
        { this.state.why && 
          <a href='/'>
            <Image src={horizontal1}
              className='pics'
            />
          </a>
        }
        { this.state.shop && 
          <a href='/'>
            <Image src={horizontal2}
              className='pics'
            />
          </a>
        }
        { this.state.workshops && 
          <a href='/'>
            <Image src={horizontal3}
              className='pics'
            />
          </a>
        }
      </div>
    );
  }
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
Malvinka
  • 1,185
  • 1
  • 15
  • 36
  • 2
    Change `setInterval(function(){` to `setInterval(() => {` and `this` will be what you expect. – Tholle Nov 19 '18 at 12:18
  • 1
    @Tholle thank you! Now I see that. If you wish to add your comment as the answer I could accept that. – Malvinka Nov 19 '18 at 12:21

1 Answers1

1

Please use fat arrow function to access constructor inside the setInterval

setInterval(()=> {
  if (this.state.why) {
    this.setState({why: false, shop: true, workshop: false})
  }
  if (this.state.shop) {
    this.setState({why: false, shop: false, workshop: true})
  }
  if (this.state.workshop) {
    this.setState({why: true, shop: false, workshop: false})
  }
}, 3000);
Tholle
  • 108,070
  • 19
  • 198
  • 189