allegutta
allegutta

Reputation: 5644

React: Define constants?

I have a container component which is feeding a presentation component with one image at a time (every time a user clicks a button). I want to define those image paths in a constant (array). But I get TypeError: Cannot read property '1' of undefined when trying to read from that array.

How can I solve that error, and is this the best approach?

export default class ImageContainer extends Component {
  constructor(props){
    super(props)
    this.state = {
      currentImage: '/images/dummy-image-1.jpg'
    }

    this.changeImage = this.changeImage.bind(this)

    const images = [
      '/images/dummy-image-1.jpg',
      '/images/dummy-image-2.jpg',
      '/images/dummy-image-3.jpg',
      '/images/dummy-image-4.jpg',
      '/images/dummy-image-5.jpg'
    ]
  }

  changeImage(event){
    console.log(this.images[1])
    //Do something
  }

  render(){
    return(
      <ImageView image={this.state.currentImage} changeImage={this.changeImage} />
    )
  }
}

Upvotes: 4

Views: 24055

Answers (2)

Rick Jolly
Rick Jolly

Reputation: 3009

You could move the const definition outside of the class:

const images = [
  '/images/dummy-image-1.jpg',
  '/images/dummy-image-2.jpg',
  '/images/dummy-image-3.jpg',
  '/images/dummy-image-4.jpg',
  '/images/dummy-image-5.jpg'
];

export default class ImageContainer extends Component {
    //...
}

This way images remains a const and it's still only visible to the code within the file (which I'll assume is just the ImageContainer class).

Upvotes: 7

madox2
madox2

Reputation: 51841

You need to define images as object property in constructor:

this.images = [
  '/images/dummy-image-1.jpg',
  ...
];

when you declare variables (using var, let, const) it is visible only in function (in your case constructor) scope.

Upvotes: 8

Related Questions