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})
}
you can achieve this with a simple trick. see what I did -
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"));
})();
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