- a plain js object.
- Most of the time they are created as JSX.
- React elements are immutable. Once you create an element, you can’t change its children or attributes.
- An element is like a single frame in a movie: it represents the UI at a certain point in time.
const element = <h1>Hello, world!</h1>;
// pass an attribute
const element = <div tabIndex="0"></div>;
const element = <img src={user.avatarUrl}></img>;
- Conceptually, it is like JavaScript function.
- It accepts arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
- Always start component names with a capital letter. React treats components starting with lowercase letters as DOM tags. For example,
<div />
represents an HTML div tag, but <Welcome />
represents a component and requires Welcome to be in scope.
- All React components must must never modify its own props, e.g. be pure functions with respect to their props.
- Class components should always call the base constructor with props.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
- Do not modify State directly.
//Wrong
this.state.comment = 'Hello';
// Correct
this.setState({comment: 'Hello'});
- State updates may be asynchronous.
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
- State updates are merged. When you call
setState()
, React merges the object you provide into the current state. The merging is shallow, so this.setState({comments})
leaves this.state.posts
intact, but completely replaces this.state.comments
.
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
}
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}