Reputation: 677
I have a special application of React to get working where I would prefer not to use JSX and Where I need to monitor clicks on links outside of React. I can't seem to get an onClick event to fire. The code I have needs to render the link inactive for the page it's on.`
var LinkCell = React.createClass({
render: function(){
var attr = {
"data-id":this.props.dataID,
"href": this.props.href,
"onClick": function(){return false}
};
var lnk = React.DOM.a(attr,this.props.href);
return React.DOM.td({},lnk);
}
});
This doesn't work and the link goes to the URL in the href. Do I have to do this in JSX?
Upvotes: 2
Views: 3374
Reputation: 1
i found the best solution for this
//like_button.js
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Click This'
);
}
}
const domContainer = document.getElementById('domContainer');
ReactDOM.render(e(LikeButton), domContainer);
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<div id="domContainer"></div>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="like_button.js"></script>
</body>
</html>
Upvotes: 0
Reputation: 677
Actually I found the solution. As you may know if a callback returns false normally you have to put inside an onclick attribute
return mycallbackfunction();
with this code I had to use preventDefault();. I don't know why I didn't try it before but thanks for the replies.
var LinkCell = React.createClass({
render: function(){
var attr = {
"data-id":this.props.dataID,
"href": this.props.href,
onClick:function(e){e.preventDefault();}
};
var lnk = React.DOM.a(attr,this.props.href);
return React.DOM.td({},lnk);
}
});
Upvotes: 2