Home > Enterprise >  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 React JS

Time:11-30

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 ;

CodePudding user response:

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,
    });
  });
}

CodePudding user response:

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

  • Related