Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda