React Base Fiddle (JSX)
Starting point for creating JSFiddles with React. This uses React with Addons.
by jesstelford
HTML
<script src="http://fb.me/JSXTransformer-0.12.1.js"></script>
<script src="http://fb.me/react-with-addons-0.12.1.js"></script>
<script src="http://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<!-- pre-rendered by React on server-side -->
<div id="content"><label data-reactid=".0" data-react-checksum="-640604677"><input type="checkbox" data-reactid=".0.0"><span data-reactid=".0.1">Foo Bar</span></label></div>
<br />
<button id="doit">Render React</button>
JavaScript 1.7
/****************
* This example shows one possible way to sync the state of the DOM with a React component, immediately after it is rendered for the first time.
*
* - Run this example
* - Togle the checkbox
* - Click "Render React"
* - The current React state is output in the console
* - Note that it is correctly { done: true }
*
* Is there a better way to sync the state from the DOM upon first render? Preferrably within the component itself, so we don't have to rely on outside code modifying state.
****************/
/*
* Our TODO item
* Note that we use 'defaultChecked' to set the checked state so the user can interact with the checkbox
*/
var TodoItem = React.createClass({
displayName: 'TodoItem',
getInitialState: function() {
return { done: this.props.done }
},
onChange: function(event) {
this.setDone(event.target.checked);
},
setDone: function(done) {
this.setState({ done: done});
},
syncStateFromDOM: function() {
this.setDone(this.refs.done.getDOMNode().checked);
},
render: function() {
return (
<label>
<input ref="done" type="checkbox" defaultChecked={this.state.done} onChange={this.onChange} />
{this.props.name}
</label>
);
}
});
// Create our renderable react component
var TodoItemFactory = React.createFactory(TodoItem);
var component = new TodoItemFactory({done: false, name: 'Foo Bar'})
// Delay browser-side rendering until button is clicked
var button = document.getElementById('doit');
button.onclick = function() {
button.setAttribute('disabled', 'disabled');
// Actually render using React browser-side
var renderedComponent = React.render(component, document.getElementById('content'));
// Sync state from the DOM
renderedComponent.syncStateFromDOM()
console.log('React state:', renderedComponent.state);
console.log('DOM state:', document.querySelector('[type=checkbox]').checked);
}