hoseh
hoseh

Reputation: 139

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>

Upvotes: 2

Views: 2033

Answers (2)

Wasi Rj
Wasi Rj

Reputation: 1

This code is for downloading any type of file having a condition if fileType is image then it will open in new tab on clicking on it. This is because it depends on user either view the image or download it.

FRONTEND (ReactJs)

const downloadFile = (fileID, fileName) => {
        axios.get(`${URL}/download/${fileID}`, { responseType: 'blob' }).then((res) => {
            const fileType = res.headers['content-type']
            const blob = new Blob([res.data], { type: fileType });
            console.log('image = ',res.data);
            const url = window.URL.createObjectURL(blob);
            if (fileType.includes('image')) {
                window.open(url)
                a.href = null;
                window.URL.revokeObjectURL(url);
            }
            const a = document.createElement('a');
            a.href = url;
            a.download = fileName;
            a.click();
            window.URL.revokeObjectURL(url);
        }).catch((err) => {
            console.log(err.message)
        });

BACKEND (ExpressJs)

app.get('/download/:id',(req,res)=>{ 
    const id = req.params.id;

    connection.query('SELECT path FROM file_table WHERE file_id=?', [id], (err, data) => {
        if (err) {
            res.status(404).json({
                message: err.message
            })
        }
        const filePath = data[0].path;
        res.download(filePath, (err) => {
            if (err) console.log(err);
            else console.log('file is downloaded');
        });
    })
})

Upvotes: 0

axtck
axtck

Reputation: 3965

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>

Upvotes: 2

Related Questions