|
|
|
|
|
by moretti
2887 days ago
|
|
By declaratively I mean that in React you typically declare how an element should be render given the current (props, [state]). For example, in vanilla JS, you might have something like: const btn = document.createElement('button');
btn.className = 'btn red';
btn.onclick = function(event) {
if (this.classList.contains('red')) {
this.classList.remove('red');
this.classList.add('blue');
} else {
this.classList.remove('blue');
this.classList.add('red');
}
};
In React instead: class Button extends React.Component {
state = { color: 'red' }
handleChange = () => {
const color = this.state.color === 'red' ? 'blue' : 'red';
this.setState({ color });
}
render() {
return (<div>
<button
className=`btn ${this.state.color}`
onClick={this.handleChange}>
</button>
</div>);
}
}
I find it simpler to understand, because render, given its state, describes exactly how the UI should be. |
|