Marek Kobida
Marek Kobida

Reputation: 11

react custom anchor component w/ do something before click functionality issue

React Component (Custom Anchor)

import React from 'react';

class Anchor extends React.Component {
  onClick = (event) => {
    // -----------------------------
    // send Google Analytics request 👌
    // -----------------------------

    if (this.props.onClick) {
      this.props.onClick(event);
    }
  }

  render () {
    return <a {...this.props} onClick={this.onClick} />;
  }
}

export default Anchor;

Example

const test1 = <Anchor href="https://www.google.com" />
// 👆 not work - did not send Google Analytics request - but open "href"

Easy solution you think? Just add event.preventDefault() to onClick function? Ok imagine we added that...

const test2 = <Anchor href="https://www.google.com" onClick=((e) => console.log(e)) />

it send Google Analytics request because we added event.preventDefault() but it did not open href

Upvotes: 1

Views: 231

Answers (1)

anvin
anvin

Reputation: 560

You can simply use event.preventDefault() in your onClick. Then do your request wait for response and set your href via window.location.href="https://www.google.com";

Example:

<a href="https://www.google.com" onClick={e =>{ e.preventDefault(); console.log("do your stuff..."); window.location.href="https://www.google.com";  }}>test</a>

Or am I missing something?

Upvotes: 1

Related Questions