Search code examples
javascriptreactjsreact-bootstrap

In ReactJS I want to call an onClick function on a button to open another website but it doesn't work


In ReactJS I want to call an onClick function on a button to open another website but it doesn't work. The following excerpt of the code is:

import PageButton from "./components/PageButton";

  const openInNewTab = (url) => {
    window.open(url, "_blank", "noopener,noreferrer");
  };
return (
    <div className="App">
      <div className="appNav">
        <div className="my-2 buttonContainer buttonContainerTop">
          <PageButton name={"Home"} isBold={true} />
          <PageButton
            name={"Test"}
            onClick={() => openInNewTab("https://www.bing.com/")}
          />
        </div>
</div>
</div>
import React from "react";

const PageButton = (props) => {
  return (
    <div className="btn">
      <span className={props.isBold ? "pageButtonBold hoverBold" : "hoverBold"}>
        {props.name}
      </span>
    </div>
  );
};

export default PageButton;

It should open the Webpage when I click on it but it doesn't.


Solution

  • If you need PageButton to handle the click, you should forward the click handler down like so:

    const PageButton = (props) => {
      return (
        <div className="btn" onClick={props.onClick}>
          <span className={props.isBold ? "pageButtonBold hoverBold" : "hoverBold"}>{props.name}</span>
        </div>
      );
    };
    
    export default PageButton;
    

    Also, I would suggest you transform the div to button as it's the right element for handling clicks.