Home > OS >  How to use the onClick Function in Next js
How to use the onClick Function in Next js

Time:11-13

I am a beginner and I am trying to learn Next js. I have a webpage which has a card and in the card i have an Arrow Right. I want a link to open when the Arrow right is clicked.

I have this code for the ArrowRight and I basically want to open a link, lets say google.com in a new tab on the click of this.

<ArrowRight
        className="heart"
        onClick={}
      />

CodePudding user response:

you can simply wrap it with "a" tag

like this :

    <a href="https://www.google.com/" target="_blank">
       <ArrowRight
        className="heart" 
      />
    </a>

or you can use Link component of nextjs

like this :

<Link href="https://google.com" rel="noopener noreferrer" target="_blank">  
      <ArrowRight
        className="heart" 
      /> 
 </Link>

CodePudding user response:

I'm not doing Next.js. But I hope this will work

 export default function SampleComponent(){
        
        const redirectPage= (e) => {
            e.preventDefault()
            document.location.href = 'https://google.com/';
        }
        return(
            <div>
                <ArrowRight
            className="heart"
            onClick={() => redirectPage()}
          />
            </div>
        )
    }

CodePudding user response:

You can do two things,

Option 1 Use Link tag,

import Link from "next/link";


<Link  href="https://www.google.com/" target="_blank">
       <ArrowRight
        className="heart" 
      />
    </Link >

second One You can use Programmatic navigation. This has two variation. If you need to route within your App.

import { useRouter } from "next/router";


const YourComponent = props => {
  const router = useRouter();

  const routeWithinYourApp = () => {
    Router.push("INTERNAL URL");
  };

  return <ArrowRight className="heart" onClick={routeWithinYourApp} />;
};

If you use external web URL, nothing special,

window.location = 'YOUR EXTERNAL LINK';

CodePudding user response:

<ArrowRight
  className="heart"
  onClick={() => window.open("google.com", "_blank")}
/>
  • Related