Sending Component Props

Sending properties to a component entails adding HTML attribute like named values to the component when it is used, not when it is defined. For example, the below Badge component is defined first. Then, to send a prop to the Badge component, name="Bill" is added to the component when it is used (i.e., when <Badge name="Bill" /> is rendered).

  1. var Badge = React.createClass({
  2. render: function() {
  3. return <div>{this.props.name}</div>;
  4. }
  5. });
  6. ReactDOM.render(<Badge name="Bill" />, document.getElementById('app'));

Keep in mind anywhere a component is used a property can be sent to it. For example, the code from the previous section demonstrates the use of the Badge component and name property from within the BadgeList component.

  1. var Badge = React.createClass({
  2. render: function() {
  3. return <div>{this.props.name}</div>;
  4. }
  5. });
  6. var BadgeList = React.createClass({
  7. render: function() {
  8. return (<div>
  9. <Badge name="Bill" />
  10. <Badge name="Tom" />
  11. </div>);
  12. }
  13. });
  14. ReactDOM.render(<BadgeList />, document.getElementById('app'));

Notes

  • A components properties should be considered immutable and components should not internally alter the properties sent to them from above. If you need to alter the properties of a component then a re-render should occur; don’t set props by adding/updating them using this.props.[PROP] = [NEW PROP].