Absolute Basics of Creating Reusable Components
suggest changeComponents and Props
As React concerns itself only with an application’s view, the bulk of development in React will be the creation of components. A component represents a portion of the view of your application. “Props” are simply the attributes used on a JSX node (e.g. <SomeComponent someProp="some prop's value" />), and are the primary way our application interacts with our components. In that example, inside SomeComponent, we would have access to this.props, whose value would be the object {someProp: "some prop's value"}.
It can be useful to think of React components as simple functions - they take input in the form of “props”, and produce output as markup. Many simple components take this a step further, making themselves “pure functions”, meaning they do not issue side effects and are deterministic (given a set of inputs, the component will always produce the same output). This goal can be formally enforced by actually creating components as functions, rather than “classes”. There are three ways of creating a React component:
- Functional (“Stateless”) Components
const FirstComponent = props => (
<div>{props.content}</div>
);
- React.createClass()
const SecondComponent = React.createClass({
render: function () {
return (
<div>{this.props.content}</div>
);
}
});
- ES2015 Classes
class ThirdComponent extends React.Component {
render() {
return (
<div>{this.props.content}</div>
);
}
}
These components are used in exactly the same way:
const ParentComponent = function (props) {
const someText = "FooBar";
return (
<div>
<FirstComponent content={someText} />
<SecondComponent content={someText} />
<ThirdComponent content={someText} />
</div>
);
}
The above examples will all produce identical markup.
Functional components cannot have state within them (this is the pre-Hooks model). If your component needs state, use a class component. Refer to Creating Components for more information.
As a final note, React props are immutable once they have been passed in, meaning they cannot be modified from within a component. If the parent of a component changes the value of a prop, React replaces the old props with the new ones, and the component rerenders using the new values.
See Thinking In React and Reusable Components for deeper dives into the relationship of props to components.