I am using react with nextjs. When I try to add onClick to link I am getting an error.
import React from 'react';
import PropTypes from 'prop-types';
import Link from 'next/link'
class Navbar extends React.Component {
render () {
return(
<div>
<Link href="/index" onClick={()=>console.log("sdf")}><a>Home</a></Link>
<Link href="/about"><a>About</a></Link>
</div>
)
}
}
export default Navbar;
Isn't this how onClick is added to links in reactjs? or is this something to do with nextjs
Yes, it is the way how to add a handler to link in React.js. But, this is a problem of Link
component from Next.js. This Link
component doesn’t have any onClick
prop. It even overrides onClick
prop of its child with its own implementation.
So, this also wouldn’t work:
<Link href="/index">
<a onClick={() => console.log('Does not work')}>Home</a>
</Link>
The simple solution could be to nest onClick
handler into another element like this:
<Link href="/index">
<a>
<span onClick={() => console.log('It works')}>Home</span>
</a>
</Link>
Or to wrap Link
with the other element, span
for example:
<span onClick={() => console.log('It also works')}>
<Link href="/index">Home</Link>
</span>
There is an open issue about it on Github: https://github.com/zeit/next.js/issues/1490.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With