React

Props

Objectives

  • Define props

  • Use props inside of a component

Props

Immutable data passed to your components

class ShowText extends Component {
  render() {
    // Inside the render method, we have
    // access to this.props (this refers
    // to the ShowText instance).

    return <div>{this.props.text}</div>;
  }
}

Accessible in your component as an object called: this.props

Passing In Props

To A Component

<ShowText
  text="This is a prop named text"
/>
class ShowText extends Component {
  render() {
    return <div>{this.props.text}</div>;
  }
}

Props Are Immutable

class ShowText extends Component {
  render() {
    // Never ever change this.props

    this.props.text = "WRONG!!";   // Causes a TypeError
    
    this.props = {}; // Never do this!!

    this.props.newProp = "Also wrong"; // Use default props

    return <div>{this.props.text}</div>;
  }
}

React Props

By Elie Schoppik

React Props

  • 2,305