3 ms·
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
by moretti 8y 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.
- petilon 8y agoThis only works for simple cases. Where this breaks down is when you have to inspect the current state of the DOM before deciding what changes to make to it. Example: scroll an element into view if it is not already visible. More examples: drag & drop, interactive resize, etc.