Lets say I have a component called MyButton. Is there a quick way to attach link behaviour to it without writing an onClick handler for every button?
Have you tried:
<MyButton to="user" />
class MyButton extends React.Component{
render() { return <Link to={this.props.to} />; }
}
MyButton is not really my button :) It could be imported from any third party UI lib. I could do things like,
class MyButton {
render() { return <Link to={this.props.to}><ThirdPartyButton {...this.props}/></Link>; }
}
or simply have Link inside the ThirdPartyButton directly everywhere or vice-versa but that doesn't seem very clean to me.
I don't like this approach but if you absolutely need this, you can set up a top-level document link handler like here:
document.onclick = event => {
const { toElement: target } = event;
if (!target) return;
if (target.tagName !== 'A') return;
const href = target.getAttribute('href');
if (!href) return;
const resolvedHref = url.resolve(window.location.href, href);
const { host, path } = url.parse(resolvedHref);
if (host === window.location.host) {
event.preventDefault();
router.transitionTo(path);
}
};
However, in my opinion, it's kinda strange to have some link components out of your control that nevertheless link to the internal routes in your app.
Agreed. onclick handlers are better :)
I haven't tried this yet, but I think you could also use one of the mixins to generate the correct link in your render function and pass that along.聽
On Sun, May 10, 2015 at 10:08 PM, Owais Lone [email protected]
wrote:
Agreed.
onclickhandlers are better :)Reply to this email directly or view it on GitHub:
https://github.com/rackt/react-router/issues/1176#issuecomment-100691459
we provide Link as a router-aware href, and mixins that have everything that link uses to work, so you can build whatever elements you want that interact with the router.
Most helpful comment
I don't like this approach but if you absolutely need this, you can set up a top-level document link handler like here:
However, in my opinion, it's kinda strange to have some link components out of your control that nevertheless link to the internal routes in your app.