How do I pass an href to an onClick function in nextjs?

Asked
Active3 hr before
Viewed126 times

9 Answers

functiononclick
90%

Whenever the about or posts page is clicked, I'd like to console.log that I clicked on the page name. Right now, my current implementation does not console.log anything. What is wrong with my code?,I would do everything on the handleClick function, even redirecting the user in a programatically way:, I've tried implementing your solution, but I can't see my console.log. Is it because the page redirects to the link and clears the console? codesandbox.io/s/nextjs-router-bfk11?file=/pages/index.js:0-541 – dev_el Jan 9 at 3:07

I would do everything on the handleClick function, even redirecting the user in a programatically way:

import { useRouter } from 'next/router'

export default function IndexPage() {
  const router = useRouter()

  const handleClick = (e, path) => {
   e.preventDefault()

    if (path === "/about") {
      console.log("I clicked on the About Page");
      // then you can: 
      // router.push(path)
    }
    if (path === "/posts") {
      console.log("I clicked on the Posts Page");
      // then you can: 
      // router.push(path)
    }
  };
}

  return (
    <div>
      Hello World.{" "}
      <Link onClick={(e) => handleClick(e, "/about")}>
        <a>About</a>
      </Link>
      <Link onClick={(e) => handleClick(e, "/posts")}>
        <a>Posts</a>
      </Link>
    </div>
  );

load more v
88%

Clicking either of those two links will not call the customHandleClick function.,This is because the onClick handler of the contained <a> tag is overridden by the next/link implementation here.,I get the point of onClick and why you need to use that. That's why we've the next/router API. Use that.

import Link from 'next/link'

const customHandleClick = () => console.log('Free pizza!')

// Somewhere in render-land

<Link href='/' onClick={customHandleClick}>
  <a>No free pizza :(</a>
</Link>

<Link href='/'>
  <a onClick={customHandleClick}>No free pizza :/</a>
</Link>
load more v
72%

Client-side transitions between routes can be enabled via the Link component exported by next/link.,passHref - Forces Link to send the href property to its child. Defaults to false,The default behavior of the Link component is to push a new URL into the history stack. You can use the replace prop to prevent adding a new entry, as in the following example:

We can have a link to each of these pages like so:

import Link from 'next/link'

function Home() {
  return (
    <ul>
      <li>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li>
        <Link href="/about">
          <a>About Us</a>
        </Link>
      </li>
      <li>
        <Link href="/blog/hello-world">
          <a>Blog Post</a>
        </Link>
      </li>
    </ul>
  )
}

export default Home
load more v
65%

Sometimes you’ll want to add a click event to the link element. You might think that passing the onClick property onto the Next Link component will work. But it doesn’t!,And I’m passing an href property to the Link component with a value that leads to the about page.,If you’d like to add a click event handler to your link, you’ll want to attach it to the HTML child element inside the Next Link component.

import Link from "next/link";

const App = () => (
  <div>
    Hello World.{" "}
    <Link href="/about">
      <a>About</a>
    </Link>
  </div>
);
load more v
75%

Pretag
 Pretag team - issue, fix, solve, resolve
40%

Handling events with React elements is similar to handling events on DOM elements, with a few minor exceptions. If you’re familiar with how events work in standard HTML and JavaScript, it should be easy for you to learn how to handle events in React.,If you’re new to React or just need a quick refresher on handling events, this video tutorial breaks down the concept quite nicely.,In JavaScript, class methods are not bound by default. Therefore, it’s necessary to bind functions to the class instance.

Pretag
 Pretag team - issue, fix, solve, resolve
22%

Next.js exposes a Link component from the next/link API that can be used to perform client-side route transitions between pages.,The next/link API exposes the Link component as a declarative way to perform client-side route transitions.,_app.js This is a custom component that resides in the pages folder. Next.js uses this component to initialize pages.

next - app├── node_modules├── pages│├── _app.js // ⚠️ Custom page (unavailable as a route)
│├── _document.jsx // ⚠️ Custom page (unavailable as a route)
│└── index.ts // path: base-url (/)
├── public├── styles├──.gitignore├── package.json└── README.md
load more v
60%

If you want to send parameters into an event handler, you have two options:,React has the same events as HTML: click, change, mouseover etc.,A good practice is to put the event handler as a method in the component class:

<button onClick={shoot}>Take the Shot!</button>
load more v
48%

Rendering a material UI button is very easy, just wrap the button component with the nextjs link component and make sure you use passHref property on the link component. ,ListItem component is used inside all kinds of material UI menus, and it is a little bit trickier to set up because the generated HTML structure of the component is more complex than a simple button component.,Link component is a magic component of next.js framework, that does the routing both client-side and server-side (properly rendering links for SEO purposes).

<Link href="/about" passHref>
<Button variant="contained" color="secondary">About</Button>
</Link>
load more v

Other "function-onclick" queries related to "How do I pass an href to an onClick function in nextjs?"