Home > OS >  Randomly Selecting an Image to Display in React
Randomly Selecting an Image to Display in React

Time:01-23

I am trying to randomly select an image to display in ReactJS (NOT React Native). I was trying to base this off of another question, but I am confused and unsure how to fix this error. Here is my code in RandomWelcomePicture.js. I am kind of new to this, so sorry if this is an easy fix.

import React, { useState } from 'react';
import image2019_0201 from '../images/2019_0201.jpeg';
import image2019_0202 from '../images/2019_0202.jpeg';
import image2019_0203 from '../images/2019_0203.jpeg';

const images = [
    image2019_0201,
    image2019_0202,
    image2019_0203,
];

class RandomWelcomePicture extends React.Component {
    state = { currentImageIndex: Math.floor(Math.random() * images.length }
  
    componentDidMount() {
      this.changeImage();
    }
        
    changeImage = () => {
      const randomNumber = Math.floor(Math.random() * images.length);
      this.setState({
        currentImageIndex: randomNumber
      });
    } 
    render() {
      return (
        <image
          source={images[this.state.currentImageIndex]}
          //style={styles.imageStyle}
        />
      )
    }
  } 

Here is my error:

ERROR in ./src/components/RandomWelcomePicture.js

Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: RandomWelcomePicture.js: Unexpected token, expected "," (13:74)

  11 |
  12 | class RandomWelcomePicture extends React.Component {
> 13 |     state = { currentImageIndex: Math.floor(Math.random() * images.length }
     |                                                                           ^
  14 |   
  15 |     componentDidMount() {
  16 |       this.changeImage();

But I don't think there should be a comma there. Is there something else I am missing?

CodePudding user response:

Your issue is conflating both a React.Component class and a functional component in one. Lets look at the code line by line to see this more clearly

export default function RandomWelcomePicture() {
// -------------^---------------- functional syntax (its a function)
    componentDidMount() {
// ---------^---------------- class syntax (defining a method)
        this.changeImage();
      }
      
  changeImage = () => {
// ---^---------------- class syntax (defining a method)
    const randomNumber = Math.floor(Math.random() * images.length);
    this.setState({
// ---^---------------- class syntax (setState)
      currentImageIndex: randomNumber
    });
  } 

  return (
// -^---------------- functional syntax (return jsx vs render method)
    <Image
        source={images[this.state.currentImageIndex]}
        style={styles.imageStyle}
    />
  )
  
} 

Now lets look at how we can change this to work in a functional way and a class component way

Functional Component

You dont need to have a componentDidMount to do what you're tying to do here.. just pass that as an initial value to your state.

export default function RandomWelcomePicture() {
  const [currentImageIndex, setCurrentImageIndex] = useState(Math.floor(Math.random() * images.length))
  const changeImage = () => {
    const randomNumber = ;
    setCurrentImageIndex(randomNumber);
  }
  useEffect(() => changeImage(), [])

  return (
    <Image
        source={images[currentImageIndex]}
        style={styles.imageStyle}
    />
  )
}

if you really do need a componentDidMount in a functional component you should do this

useEffect(() => changeImage(), []) // empty array means this effect only runs once which is the same thing as componentDidMount

Class Component

class RandomWelcomePicture extends React.Component {
  state = { currentImageIndex: Math.floor(Math.random() * images.length }

  componentDidMount() {
    this.changeImage();
  }
      
  changeImage = () => {
    const randomNumber = Math.floor(Math.random() * images.length);
    this.setState({
      currentImageIndex: randomNumber
    });
  } 
  render() {
    return (
      <Image
        source={images[this.state.currentImageIndex]}
        style={styles.imageStyle}
      />
    )
  }
} 
  •  Tags:  
  • Related