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 the snippet above, inside of 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 idempotent (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:
const FirstComponent = props => (
<div>{props.content}</div>
);
const SecondComponent = React.createClass({
render: function () {
return (
<div>{this.props.content}</div>
);
}
});
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 (
<FirstComponent content={someText} />
<SecondComponent content={someText} />
<ThirdComponent content={someText} />
);
}
The above examples will all produce identical markup.
Functional components cannot have "state" within them. So if your component needs to have a state, then go for class based components. Refer 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 handles replacing the old props with the new, the component will rerender itself using the new values.
See Thinking In React and Reusable Components for deeper dives into the relationship of props to components.