Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React <a> tag and button onClick propagation

I want to create a React component with a render method that has an <a> tag that wraps an entire "box", if you will, which redirects to another page when clicked. Within said box there is a <button> that can be clicked that activates an event that changes state. What I want to be able to do is click the <button> and trigger the event without the redirect from the <a> tag occurring.

Tried some ideas with stopPropagation() but no luck :/ I don't want to move the button outside of the <a> tag either so not sure where to go from here.

It seems like it should be something simple but I just can't figure it out. Thanks!

the render method looks like this:

render(){
 return(
  <div>
   <a href="http://www.google.com"> 
    <div className="box">

     <h2 className="title">Random Title</h2>

     <button onClick={this.handleClick}> Like </button>

    </div>  
   </a>
  </div> 
 )
}

handleClick() would look something like this:

handleClick = () => {
  if (this.state.liked) {
  console.log("disliking")
} else {
  console.log("liking")
}

this.setState({ liked: !this.state.liked})
}
like image 780
JAbrams Avatar asked Jan 16 '17 01:01

JAbrams


1 Answers

you can achieve this with a simple trick. see what I did -

  1. replace the anchor with a div and place a click handler
  2. add a flag (clicked) with in the component and ignore in div click handler if it's a button click
  3. reset the flag

update - check out this js fiddle : https://jsfiddle.net/rabinarayanb/pvx2n3x3/

note - I have used es5 syntax. you can convert to es6

(function() {   
    var BoxSetup = React.createClass({


        clicked : "",

        getInitialState : function () {
            return { clickCount : 0};
        },

        handleDivClick : function (event) {
            if (this.clicked !== "Button") {
                window.location.href = "http://www.google.com";
            }

            // reset
            this.clicked = "";
        },

        handleButtonClick : function (event) {
           this.clicked = "Button"
           this.setState({
                clickCount : ++this.state.clickCount
           });
        },

        render : function () {

            return (
            <div>
                <div onClick={this.handleDivClick} style={ { }}>
                    <div style={ { width : "100px", height : "100px", border : "1px solid red" } }>
                        <h2 className="title">{ this.state.clickCount }</h2>
                        <button onClick={this.handleButtonClick}> Like </button>
                    </div>
                </div>
            </div> 
            );
        }
    });

    var element = React.createElement(BoxSetup, { title : "Hello" });

    ReactDOM.render(element, document.getElementById("app"));    
})();
like image 163
Rabi Avatar answered Oct 24 '22 21:10

Rabi