What Are Component Props?

The simplest way to explain component props would be to say that they function similarly to HTML attributes. In other words, props provide configuration values for the component. For example, in the code below a Badge component is created and it is expecting a ‘name’ prop to be sent when the component is instantiated.

source code

Inside the render function of the <BadgeList> component, where <Badge> is used, the name prop is added to the <Badge> component much like an HTML attribute is added to an HTML element (i.e., <Badge name="Bill" />). The name prop is then used by the Badge component (i.e., this.props.name) as the text node for the React <div> node rendered by the Badge component. This is similar to how an <input> can take a value attribute which it uses to display a value.

Another way to think about component props is that they are the configuration values sent to a component. If you look at the non-JSX version of the previous code example it should be obvious component props are just an object that gets passed to the createElement() function (i.e., React.createElement(Badge, { name: "Bill" })).

  1. var Badge = React.createClass({
  2. displayName: "Badge",
  3. render: function render() {
  4. return React.createElement(
  5. "div",
  6. null, //no props defined, so null
  7. this.props.name //use passed this.prop.name as text node
  8. );
  9. }
  10. });
  11. var BadgeList = React.createClass({
  12. displayName: "BadgeList",
  13. render: function render() {
  14. return React.createElement(
  15. "div",
  16. null,
  17. React.createElement(Badge, { name: "Bill" }),
  18. React.createElement(Badge, { name: "Tom" })
  19. );
  20. }
  21. });
  22. ReactDOM.render(React.createElement(BadgeList, null), document.getElementById('app'));

This is similar to how props can be set directly on React nodes (see 4.4 and 5.7). However, when the createElement() function is passed a component definition (i.e., Badge) instead of a node, the props become available on the component itself (i.e., this.props.name). Component props make it possible to re-use the <Badge> component with any name.

In the previous code example examined in this section, the BadgeList component uses two Badge components each with their own this.props object. We can verify this by console logging out the value of this.props when a Badge component is instantiated.

source code

Basically every React component instance has a unique instance property called props that starts as an empty JavaScript object. The empty object can get filled, by a parent component, with any JavaScript value/ reference. These values are then used by the component or passed on to child components.

Notes

  • In ES5 environments/engines you won’t be able to mutate this.props because its frozen (i.e., Object.isFrozen(this.props) === true; ).
  • You should consider this.props to be readonly.