4 ms·
The example isn't real-world scenario. TBH, I'd say it's anything but enlightening. What React does, is keeping the DOM tree in sync with the data (components'
by drdaeman 10y ago
The example isn't real-world scenario. TBH, I'd say it's anything but enlightening.
What React does, is keeping the DOM tree in sync with the data (components' states and properties). If you don't have the state - it might be the case that you don't really need React, something like Handlebars.js or jQuery templates (if there's even a need for templating at all) would do just fine.
I mean, there's no real practical difference[1] between something like
// A stateless React component, so no need for React.Component boilerplate
const MySelect = (props) =>
<select name={props.name}>
{ props.values.map((v, i) => <option value={i+1}>{v}</option>) }
</select>;
// For this example to be short, no trees here. Only one component.
// (although internally <select> and <option>s are - but we don't care yet)
// And, actually, in my opinion React only starts to make sense
// when there's a big enough hierarchy of components (stateful or not).
ReactDOM.render(<MySelect name="x" values={["foo", "bar"]} />, targetEl);
And something like
const MySelectT = Handlebars.compile(`
<select name={{name}}>
{{#values}}<option value="{{@index}}">{{.}}</option>{{/values}}
</select>`);
// Same as ReactDOM.render for one-component case. For nested, use {{include}}
// However, note now here's an important difference - unless the templating
// library is more powerful, the state is monolithic (and has to be defined
// implicitly, in full) with this approach.
$(targetEl).html(MySelectT({name: "x", values: ["foo", "bar"]}));
[1]: But there's no difference only when you keep it at this level.
But if your UI is dynamic enough and you start to care about the state (e.g. you don't want to lose user input to template re-rendering, when user switches the tabs back and forth) - React provides a way to handle this by one-way binding between your data structure and DOM tree it handles. All it does, though, is only handling of that DOM tree and handling/propagating state updates (esp. if you combine it with Redux) - all the rest is yours to code.