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

Time:07-22

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" onm ouseEnter={() => setImage(image1) }></button>
      <button type="button" onm ouseEnter={() => setImage(image2) }></button>
      <button type="button" onm ouseEnter={() => setImage(image3) }></button>
      <button type="button" onm ouseEnter={() => setImage(image4) }></button>
   </div>
   <div>
      <img src={image} />
   </div>
    );
  }
export default App;

CodePudding user response:

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)
  • Related