Defining points:
Components are:
It allows you to split a complex problem in multiple simpler ones.
import React from "react";
class Button extends React.Component {
render() {
return <div className="button"></div>;
}
}Minimal component
Highlights:
Properties are:
class Button extends React.Component {
render() {
return (
<div className="button" onClick={this.props.onClick}>
{this.props.text}
</div>
);
}
}
Button.defaultProps = {
text: "Default Button Text",
onClick: () => {}
};class CheckBox extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
checked: false
};
}
render() {
return (
<input type="checkbox"
checked={this.state.checked}
onClick={this.handleChange.bind(this)} />
);
}
}Initialization:
State changes:
Props changes:
Unmounting:
this.props.children
You can use the utility methods from React.Children:
Handling children:
// simple approach
render() {
return <div>{this.props.children}</div>;
}
// adding or modifying child properties
render() {
return <div>{this.renderChildren()}</div>;
}
renderChildren() {
return React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, {
key: child.props.id, // an id uniq to the child
overridenProp: "newVal",
newProp: "someVal"
});
});
}
// checking for a child type
renderChildren() {
return React.Children.map(this.props.children, (child) => {
// only render CheckButton 's
if (child.type == CheckButton) {
return child;
}
});
}Refs or references:
JSX
Refs break the encapsulation principle, try to avoid using them.
import ReactDOM from "react-dom";
class Container extends React.Component {
// accessing refs
componentDidMount() {
this.refs.title; // DOM node
this.tabView = $.tabView(this.refs.title);
this.refs.button; // React component instance
ReactDom.findDOMNode(this.refs.button); // DOM node
}
// attaching refs
render() {
return (
<div>
<span ref="title">Foo</span>
<MyComponent ref={(el) => {/**/}}
<Button ref="button"/>
</div>
);
}
componentWillUnmount() {
this.tabView.distroy();
}
}