Reputation: 567
Please consider that I'm a begineer to React and I have only some basic knowledge in React and this is a sample project which I'm doing to learn React. Here I'm trying to view how many times the "Like" button is clicked at dynamically. I've tried it in several ways but I was unable to do what I want. How ever I was managed to get the result by clicking on another button called "Refresh" then show the result. I have attached my code herewith. If anyone who can help to find a solution in this matter is much appretiatable.
html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="like_button_container"></div>
<div id="refresh_button_container"></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="js/like_button.js"></script>
</body>
</html>
like_button.js
let e = React.createElement;
let count = 0;
class Like_button extends React.Component {
constructor(props) {
super(props);
this.state = {liked: false};
}
render() {
if (this.state.liked) {
count++;
}
return e('button', {onClick: () => this.setState({liked: true})}, 'Like')
}
}
class Refresh_button extends React.Component {
constructor(props) {
super(props);
this.state = {liked: false};
}
render() {
if (this.state.liked) {
return 'You Liked This '+ count+ ' Times!';
}
return e('button', {onClick: () => this.setState({liked: true})}, 'Refresh')
}
}
let likeButton = document.querySelector('#like_button_container');
ReactDOM.render(e(Like_button), likeButton);
let backButton = document.querySelector('#refresh_button_container');
ReactDOM.render(e(Refresh_button), backButton);
Upvotes: 1
Views: 1353
Reputation: 111
There may be a reason for this approach, so I'll leave out discussion of using jsx. If you want to keep going with createElement, how about this?
let e = React.createElement;
let count = 0;
class Like_button extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
count++;
}
return e(
'div',
null,
e('button', { onClick: () => this.setState({ liked: true }) }, 'Like'),
e('div', null, 'You Liked This ' + count + ' Times!')
);
}
}
let likeButton = document.querySelector('#like_button_container');
ReactDOM.render(e(Like_button), likeButton);
This will create a parent div with the button and display elements as children. Not sure how you were originally trying to show the 'You Liked This...' text. I've put it in as an additional div element.
If you don't want that extra parent div in the DOM:
render() {
if (this.state.liked) {
count++;
}
return e(
React.Fragment,
null,
e('button', { onClick: () => this.setState({ liked: true }) }, 'Like'),
e('div','You Liked This ' + count + ' Times!')
);
}
Upvotes: 1