Home > Back-end >  In ReactJS I want to call an onClick function on a button to open another website but it doesn'
In ReactJS I want to call an onClick function on a button to open another website but it doesn'

Time:11-07

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.

CodePudding user response:

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.

CodePudding user response:

can you use tag a inside the button like this

<button .... > <a href="..." target="_blank"> text<a/> </button>

CodePudding user response:

At PageButton component, you need to add click event for Warpper.

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

export default PageButton;
  • Related