02: Component architecture: Composition!
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
We can do better: JSX?
Returned from a "render" function in the JS class:
Requires Babel (or similar)—I take care of it for now
render() {
return (
<div>
<p>Hello</p>
</div>
);
}// ES2015 class syntax
class Greeting extends React.Component {
render() {
return (
// JSX
<p>Hello, {this.props.name}</p>
);
}
}
// NB: JSX
var greeting = <Greeting name="Martin" />;
// Add the element to the DOM
ReactDOM.render(
greeting,
document.getElementById('container')
);constructor(props) (duh)
componentWillMount()
componentDidMount()
render()
class Counter extends React.Component {
constructor(props) {
super(props);
// define state object with defaults in constructor
this.state = {
count: 0,
};
}
componentWillMount() {
setInterval(
() => this.setState({count: this.state.count + 1}),
1000
);
}
render() {
return (
<h1>{this.state.count}</h1>
);
}
}
ReactDOM.render((
<Counter />
), document.getElementById('container'));class Counter extends React.Component {
constructor(props) {
super(props);
// define state object with defaults in constructor
this.state = {
count: 0,
};
}
componentWillMount() {
setInterval(
() => this.setState({count: this.state.count + 1}),
1000
);
}
render() {
return (
<h1>
{this.state.count}
</h1>
);
}
}Component that consists of only other components
ReactDOM.render((
<A>
<B /> {/* "Child" node: passed to A as props.children */}
</A>
), document.getElementById('container'));
class B extends React.Component {
render() {
return (
<div>
<h1>Heading</h1>
<p>Body text</p>
</div>
);
}
}
class A extends React.Component {
render() {
return (
<div style={{padding: '1em', border: 'solid black 1px'}}>
{this.props.children} {/* Render B */}
</div>
);
}
}General, reusable wrappers!
var arr = [{v: 1}, {v: 2}, {v: 3}];
var numbersOnly = arr.map(element => element.v);
// [1, 2, 3]people.map(person => (
<div>
<h1>{person.name}</h1>
<p>Occupation: {person.occupation}</p>
</div>
));// somewhere
window.state = {
albums: ['Kintsugi', 'Transatlanticism'];
};
// another file
const albums = window.state.albums;// somewhere
function print() {
console.log(this.text);
}
// elsewhere
class Hello {
constructor() {
this.text = 'hello, world!';
const bound = print.bind(this);
bound();
}
}Reactify with proper validation:
Bonus: Show has-error on form-group (bootstrap)