Junfeng Liu
2017-06-23
Components are the main building block of a React application.
A component represents a self-contained piece of UI.
Display some data and be able to handle some kind of user interaction.
Make complex components from simpler components.
Composable, reusable, maintainable, testable.
Data flows only in one direction: down the tree.
Never 'update' or 'mutate' the DOM. We simply re-render it.
Props are immutable, handed from parent to child.
State is mutable and changes trigger re-render.
props
state
render
Virtual DOM
DOM
Component
Element tree (JSX)
JSX isn’t some wild idea. It’s a natural progression.
const element = <h1 className="greeting">Hello, world!</h1>;
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
const element = <img src={user.avatarUrl}></img>;
ReactDOM.render(element, document.getElementById('root'));
JSX produces React “elements”.
You can embed any JavaScript expression by wrapping it in {}.
JSX is an expression too.
const sampleComponent = () => {
return isTrue && <p>True!</p>;
};
const sampleComponent = () => {
return isTrue ? <p>True!</p> : <p>False!</p>;
};
// do expression on stage-1
const sampleComponent = () => {
return (
<div>
{
do => {
if (flag && flag2 && !flag3) {
if (flag4) {
<p>Blah</p>
} else if (flag5) {
<p>Meh</p>
} else {
<p>Herp</p>
}
} else {
<p>Derp</p>
}
}
}
</div>
)
};
const SearchSuggestions = (props) => {
// renderSearchSuggestion() behaves as a pseudo SearchSuggestion component
// keep it self contained and it should be easy to extract later if needed
const renderSearchSuggestion = listItem => (
<li key={listItem.id}>{listItem.name} {listItem.id}</li>
);
return (
<ul>
{props.listItems.map(renderSearchSuggestion)}
</ul>
);
};
Element
Component
const element = <div />;
const element = <Welcome name="Sara" />;
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
User-Defined Components Must Be Capitalized
Events flow up, data flows down