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

Change img source in React using onMouseEnter while having a default picture

I am currently working on this where i have 4 buttons and each of them changes the image in a separate div. I have almost done it, though when the page reloads the image is blank and shows only when i hover over a button. I want the picture to be defaulted to the first option on page reload.

function App() {
  const [image, setImage] = useState('')

  return (
   <div>
      <button type="button" onMouseEnter={() => setImage(image1) }></button>
      <button type="button" onMouseEnter={() => setImage(image2) }></button>
      <button type="button" onMouseEnter={() => setImage(image3) }></button>
      <button type="button" onMouseEnter={() => setImage(image4) }></button>
   </div>
   <div>
      <img src={image} />
   </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

Currently the default initial value is an empty string:

const [image, setImage] = useState('')

Change it to one of the values you want to use:

const [image, setImage] = useState(image1)
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