Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Onclick=window.open() function will open a new page every time I refresh the page?

So I have a DIV element that, when pressed, I want to open a new tab in a different window. The only problem is, whenever the page is refreshed or any other div element is pressed, th function is initiated as well and opens a page in another window. I'll include my code below, but I'm not sure why this is happening seeing as how I'm using onClick={window.open("https://www.thechinesewriter.com") Like I said, I only want a new tab to open when the div is pressed, not when any other items on the page are clicked or even when the page itself is refreshed.

import React from "react";
import "./Column1.css";

class Column1 extends React.Component {

    render() {
        return(
            <React.Fragment>
                 <div className="rectImage">
                     <img className="imagePost" src={this.props.image} />   
                 </div>
                 <div onClick={window.open("https://www.thechinesewriter.com")} className="downloadBut1">
                     <h2>
                         Source
                     </h2>
                 </div>
                 <div className="downloadBut2">
                     <h2>
                         Repository
                     </h2>
                 </div>
             </React.Fragment> 
         )
     }     
}

export default Column1;
like image 811
Laurel Link Avatar asked Jan 19 '26 22:01

Laurel Link


1 Answers

You need to call the function as a callback like this.

<div onClick={() => window.open("https://www.thechinesewriter.com")} className="downloadBut1">

Otherwise this gets called every time the component gets rendered.

like image 122
Mark Avatar answered Jan 22 '26 12:01

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!