4 ms·
It’s interesting that you find this “simpler”. One of the great advantages of React is that is declarative, it’s easy to understand how a component will render
by moretti 8y ago
It’s interesting that you find this “simpler”. One of the great advantages of React is that is declarative, it’s easy to understand how a component will render given a set of (props, state). Your example is quite the opposite, the render method violates this principle and each event handler manipulates the DOM using a ref. I’d call this spaghetti-React.
- petilon 8y agoDid you miss the fact that this component is interactive? You can't do interactivity declaratively.
- moretti 8y agoBy 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.