Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Switching pictures with onClick in React

I’m trying to switch between pictures every time I click on the button, any idea what’s wrong with my code.

import "./App.css";
import { useState } from "react";

function App() {
  const [picture, setPicture] = useState();

  const ChangePicture = () => {
    setPicture([
      "http://www.clker.com/cliparts/n/8/K/L/T/C/number-1-md.png",
      "https://image.shutterstock.com/image-vector/number-2-icon-vector-illustration-600w-549182386.jpg"
    ]);
  };

  return (
    <div className="App">
      <img src={picture} />
      <button onClick={ChangePicture}>Change Picture</button>
    </div>
  );
}

export default App;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you store image urls into an array, you can toggle between and display the image corresponding to the selected index:

import './App.css';
import { useState } from 'react';

const pictures = [
  'http://link.com/image1.png',
  'http://link.com/image2.png',
];

function App() {
  const [pictureIdx, setPictureIdx] = useState(0);

  const changePicture = () => {
    setPictureIdx((prevIdx) => {
      return (prevIdx + 1) % pictures.length;
    });
  };

  return (
    <div className='App'>
      <img src={pictures[pictureIdx]} />
      <button onClick={() => changePicture}>Change Picture</button>
    </div>
  );
}

export default App;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading