React Base Fiddle (JSX)
Starting point for creating JSFiddles with React. This uses React with Addons.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/JSXTransformer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/react-with-addons.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<h1>Singleton components in React</h1>
<p>The following React component, named NotificationCenter, has a static array of notifications to display. It is only ever mounted in one place in the application. We take advantage of that fact by saving a static reference to that component instance so that when the static array of notifications to display is updated, we know what to forceUpdate.</p>
<div id='container'>
</div>
<div id='button-container'>
</div>
CSS
p {
max-width: 500px;
}
JavaScript 1.7
var NotificationCenter = (function() {
// Private static list of notifications to render in the Singleton component
var notifications = [];
// Private static reference to the latest (usually the only) instance of NotificationCenter that mounted.
var mountedInstance;
var NotificationCenter = React.createClass({
componentDidMount: function() {
// Assign this to mountedInstance on mount
mountedInstance = this;
},
render: function() {
return (
<ul className='NotificationCenter'>
{notifications.map(function(notification) {
return <li>{notification}</li>;
})}
</ul>
);
}
});
NotificationCenter.addNotification = function() {
notifications.push('another notification');
mountedInstance.forceUpdate();
};
return NotificationCenter;
})();
React.render(<NotificationCenter />, document.getElementById('container'));
React.render((
<button onClick={NotificationCenter.addNotification}>Add notification</button>
), document.getElementById('button-container'));