Getting Component Props

As discussed in section 6.4 a component instance can be accessed from any configuration option that uses a function by way of the this keyword. For example, in the code below the this keyword is used to access the Badge props from the component render configuration option (i.e., this.props.name).

  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'));

Nothing that difficult to grasp is happening if you look at the transformed JavaScript (i.e., JSX to JS)

  1. var Badge = React.createClass({
  2. displayName: "Badge",
  3. render: function render() {
  4. return React.createElement(
  5. "div",
  6. null,
  7. this.props.name
  8. );
  9. }
  10. });
  11. ReactDOM.render(React.createElement(Badge, { name: "Bill" }), document.getElementById('app'));

The { name: "Bill" } object is sent to the createElement() function along with a reference to the Badge component. The value { name: "Bill" } is set as an instance property value of the component accessible from the props property (ie. this.props.name === "Bill").

Notes

  • You should consider this.props to be readonly, don’t set props using this.props.PROP = 'foo'.