Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
Randomly Selecting an Image to Display in React

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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}
      />
    )
  }
} 
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda