Hybrid stateless React components
by dannyjolie
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.min.js"></script>
<div id="app"></div>
CSS
html, body {
margin: 0;
}
body {
padding: 20px;
background-color: white;
font-family: Monaco, 'Courier New', monospace;
}
.hybrid {
padding: 20px;
border: 1px solid skyblue;
border-radius: 3px;
margin-bottom: 20px;
}
.from-parent {
padding: 5px;
background-color: lightgray;
}
Babel + JSX
const FieldCatalogue = {
name: function(){
// This component does not have any state
// but when bound to its parent it can use this.state.userProfile
return (
<div className="hybrid">
<p>This is a hybrid stateless component</p>
<p className="from-parent">{`Parent's state name: ${this.state.userProfile.name}`}</p>
</div>
);
},
age: function(){
// The same goes for this one.
return (
<div className="hybrid">
<p>This is another hybrid stateless component</p>
<p className="from-parent">{`Parent's state age: ${this.state.userProfile.age}`}</p>
</div>
);
}
}
const App = React.createClass({
getInitialState: function(){
return {
userProfile: {
name: 'Daniel',
age: '34'
}
};
},
render: function() {
let content = Object.keys(FieldCatalogue).map((objkey, i) => {
let Tmp = FieldCatalogue[objkey].bind(this); // Bind the components to 'this'
return <Tmp key={i} />;
});
return (
<div>
<h1>Hybrid stateless React components</h1>
<p>Small demo of context aware stateless components that do not take any props, but consume the parent component's state directly.</p>
{content}
</div>
);
}
});
ReactDOM.render(<App />, document.getElementById('app'));