Components
Let you split the UI into independent, reusable pieces, and think about each piece in isolation.
They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
Composing Components
Lifecycle
Lifecycle — Special methods on the component class to run some code when a component mounts and unmounts.
Class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
Conditional Rendering
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
ReactDOM.render(
// Try changing to isLoggedIn={true}:
<Greeting isLoggedIn={false} />,
document.getElementById('root')
);
You can render only some of components, depending on the state of your application.
Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them.
Forwarding Refs
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
Is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.
Autobinding
//with ES6
class SayHello extends React.Component {
constructor(props) {
super(props);
this.state = {message: 'Hello!'};
// This line is important!
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
alert(this.state.message);
}
render() {
// Because `this.handleClick` is bound, we can use it as an event handler.
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
}
//without ES6
var SayHello = createReactClass({
getInitialState: function() {
return {message: 'Hello!'};
},
handleClick: function() {
alert(this.state.message);
},
render: function() {
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
});
In React components declared as ES6 classes, methods follow the same semantics as regular ES6 classes. This means that they don’t automatically bind this to the instance. You’ll have to explicitly use .bind(this) in the constructor.
With createReactClass(), using .bind(this) in the constructor is not necessary because it binds all methods.
Related concepts
- Components: Composing Components
- State
- Components: Conditional Rendering
- Basic List Component: Extracting Components with Keys
- Controlled Components
- State: Lifting State Up
- Context
- Context.Provider
- Error Boundaries
- Higher-Order Component
- Container components
- Components: Forwarding Refs
- Components: Autobinding
- Uncontrolled Components
- Web Components
- Web Components: Using Web Components in React
- Web Components: Using React in your Web Components
- React Without ES6: Mixins in React without ES6
- Ref: Refs and Function Components
- Render Prop
- Flow Type Checker
- StrictMode: Identifying unsafe lifecycles
- StrictMode: Warning about deprecated findDOMNode usage
- React.memo
- React.Children: React.Children.count
- React.forwardRef
- ReactDOM: render()
- ReactDOM: findDOMNode()
- ReactDOMServer
- React DOM Elements: checked
- React DOM Elements: selected
- React DOM Elements: value
- ReactTestUtils
- Shallow Rendering
- ReactTestUtils: findAllInRenderedTree()
- ReactTestUtils: scryRenderedDOMComponentsWithClass()
- ReactTestUtils: scryRenderedDOMComponentsWithTag()
- ReactTestUtils: scryRenderedComponentsWithType()
- Touchables
- ScrollView
- User Interface
- Shallow Rendering: shallowRenderer.render()
- Test Renderer
- Test Renderer: testRenderer.toJSON()
- Test Renderer: testRenderer.toTree()
- Test Renderer: testInstance.instance
- Components: Lifecycle
- Props
- Fragments
- Basic List Component
- Handling Events
- View
- Text
- Image
- TextInput
- StyleSheet
- StatusBar