Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow the customized onClick #3997

Closed
wants to merge 3 commits into from

Conversation

haohcraft
Copy link

@haohcraft haohcraft commented Mar 12, 2018

For our use case, we need to fire our Analytics related calls when people click the link. The current onClick in Next/Link does not allow us to easy to do that. We have to something like:

const Link = ({ onClick, href, children, ...rest }) => (
  <span onClick={onClick} {...rest}>
		<NextLink route={href} >
			<span>{children}</span>
		</NextLink>
	</span>
)

And later on

<Link href='/abc' onClick={onImageClick}>
  <ImageComponent content="something random" />
</Link>

Note, we can not do the below, because of this overrides my onClick callback. 😢

<Link href='/abc' >
  <ImageComponent content="something random" onClick={onImageClick} />
</Link>

It would be helpful, we would accept customized onClick callback on NextLink.

@prichodko
Copy link
Contributor

prichodko commented Mar 12, 2018

Does this work ?

<Link href='/abc'>
  <a onClick={onImageClick}>
    <ImageComponent content="something random" />
  </a>
</Link>

@haohcraft
Copy link
Author

@prichodko Nope, because this will override your onClick call.

@timneutkens
Copy link
Member

You can do something like this, it's more flexible since the handler can also be async. And it requires no core changes.

import NextLink from 'next/link'

const LinkWrapper = ({href, onClick, passedOnClick, children}) => {
  const wrappedOnclick = (...args) => {
    passedOnClick(...args)
    // your own code here, this function can even be async
    return onClick(...args)
  }

  return <a href={href} onClick={wrappedOnclick}>{children}</a>
}

const Link = ({children, onClick: passedOnClick, ...props}) => {
  return <NextLink {...props}>
    <LinkWrapper href={props.as || props.href} passedOnClick={passedOnClick}>
      {children}
    </LinkWrapper>
  </NextLink>
}

export default () => {
  return <div>
    <Link href="/about" onClick={() => console.log('TEST')}>test</Link>
  </div>
}

@haohcraft
Copy link
Author

thanks for the suggestion, will play with it.

@lock lock bot locked as resolved and limited conversation to collaborators May 16, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants