Class component
import React, { useState } from 'react';
class ClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
likes: 0,
};
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}
increment() {
this.setState({ likes: this.state.likes + 1 });
}
decrement() {
this.setState({ likes: this.state.likes - 1 });
}
render() {
return (
<div>
<>Likes <b>{this.state.likes}</b></>
<button onClick={this.increment} style={btnCss}> +1 </button>
<button onClick={this.decrement} style={btnCss}> -1 </button>
</div>
)
}
}
<ClassComponent />
Function component Function component is a modern way to write a component in react.
import React, { useState } from 'react';
function FunctionComponent() {
const [likes, setLikes] = useState(0);
const increment = () => setLikes(likes + 1);
const decrement = () => setLikes(likes - 1);
return (
<div>
<div>Likes <b>{likes}</b></div>
<button onClick={increment} style={btnCss}> +1 </button>
<button onClick={decrement} style={btnCss}> -1 </button>
</div>
)
}
<FunctionComponent />