I am studying React now and I have a little doubt. What is the difference between the 2? From what I've seen, they both do the same thing.
I am studying React now and I have a little doubt. What is the difference between the 2? From what I've seen, they both do the same thing.
It seems to me that your question is not specific to React, but rather to the JavaScript language. Anyway, I'll explain the two cases.
(1) In the case of own language
Before the ECMAScript 2015 (also called "ES6"), there was no building of class
in JavaScript.
The class keyword was added in ES6, allowing you to define classes in JavaScript. But in fact, it's nothing more, nothing less than a syntactic sugar for the old Function
, as the example below demonstrates:
class Hello {}
Hello.constructor // => ƒ Function() { [native code] }
(2) In the case of the React library
In React you can define a component using a function or a class.
(a) stateless functional component
The simplest way to define a React component is by using a function. A component defined in this way does not maintain state or contain lifecycle methods. Here's the example:
const Botao = (props) => {
return (
<button type="button">{props.children}</button>
);
};
I used an arrow function above, but I could also have used the old function(props) {}
. The value returned by the function defines the model (view) of the component.
(b) class component
Another more sophisticated way to build a React component is by using an ES6 class. Note that before ES6, staff used React.createClass()
because there were no classes. Here is an example:
class Botao extends React.Component {
render() {
return (
<button type="button">{this.props.children}</button>
);
}
}
Note that a class component needs the render()
method, which defines the component model. Class components allow you to define a state to store information, accessible via this.state
. You can also define lifecycle components in class components (e.g. componentDidMount()
). Here is an example of a counter:
class Contador extends React.Component {
constructor(props) {
super(props);
this.state = {
contagem: 0,
};
this.onCounterClick = this.onCounterClick.bind(this);
}
onCounterClick() {
this.setState({ contagem: this.state.contagem + 1 });
}
render() {
return (
<button type="button" onClick={this.onCounterClick}>Contagem: {this.state.contagem}</button>
);
}
}
The example above shows a button whose text contains a counter starting from zero. Each time you click the button, the count increases by 1.