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

191
Vistas
I want the image to change when i click the button in class component React JS

I want the image to change when i click the button in class component. I know function component but how can i do this ?

 class Coffies extends React.Component{
      
        constructor(props){
            super(props)
            this.state={
                giphy:[],
                loading:false
            }
        }
        componentDidMount(){
          const apiURL = "https://api.giphy.com/v1/gifs/random";
          const apiKEY = "bi3FFnNepwMz5HlDYwCfvyhXQLGrvVtL";
          const randomIndex = Math.floor(Math.random()*50);
            axios(`${apiURL}?api_key=${apiKEY}`)
            .then((response)=> this.setState({
              giphy : response.data.data.images.fixed_height.url, 
              loading: true
            }))
           
    
        }
        render(){
            return (
                <>
    
                        <img
                          className="cats-img"
                          src={this.state.giphy}
                          alt="Loading.."
                        />
                        <button onClick={()=> this.setState({loading : false})} className="mt-5 py-3 btn generate-btn">
                          Get Random Cat Images
                        </button>
    
            </>
            )
        }
    }
    export default Coffies ;
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can change the image on click of the button, if you create a method changeImage

changeImage = () => {
  this.setState({
    loading: true,
  });
  this.getImage();
};

Live Demo

Codesandbox Demo

and call the getImage method in it

getImage() {
  const apiURL = "https://api.giphy.com/v1/gifs/random";
  const apiKEY = "bi3FFnNepwMz5HlDYwCfvyhXQLGrvVtL";
  axios(`${apiURL}?api_key=${apiKEY}`).then((response) => {
    this.setState({
      giphy: response.data.data.images.fixed_height.url,
      loading: false,
    });
  });
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

ComponentDidMount() only runs once in general, so it's not a good place to put your image loading logic. You should place your logic inside an onClick handler:

<button onClick={changeImage} className="mt-5 py-3 btn generate-btn">Get Random Cat Images</button>

which then calls the function suggested by @decpk

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