Search code examples
reactjshyperlinktabsonclickhref

Opening new tab upon clicking image for ReactJS


I'm trying to open a new link (in this case, i've just included a dummy link : facebook.com) on a new tab upon clicking on the hover-img class. But I'm facing some trouble doing it. Below is a snippet of my code, would gladly appreciate the help.

<div className="container">
  {data.map((d)=>(
    <div className="item">
      <img className="background-img" src={d.img} ></img>
      <h3>{d.title}</h3>
      <img 
        className="hover-img" 
        href="www.facebook.com" 
        src="asset/eye.png"
      />
    </div>
  ))}
</div>

Solution

  • Instead of setting the href attribute, you could open a new window with window.open() on click.

    <div className="container">
    {data.map((d)=>(
         <div className="item">
           <img className="background-img" src={d.img} ></img>
           <h3>{d.title}</h3>
           <img 
             className="hover-img" 
             src="asset/eye.png" 
             alt="eye" 
             onClick={()=> window.open("https://www.facebook.com", "_blank")} 
           />
         </div>
        ))}
    </div>