Props

suggest change

Props are a way to pass information into a React component, they can have any type including functions - sometimes referred to as callbacks.

In JSX props are passed with the attribute syntax

<MyComponent userID={123} />

Inside the definition for MyComponent userID will now be accessible from the props object

// The render function inside MyComponent
render() {
    return (
        <span>The user's ID is {this.props.userID}</span>
    )
}

It’s important to define all props, their types, and where applicable, their default value:

// defined at the bottom of MyComponent
MyComponent.propTypes = {
    someObject: React.PropTypes.object,
    userID: React.PropTypes.number.isRequired,
    title: React.PropTypes.string
};

MyComponent.defaultProps = {
    someObject: {},
    title: 'My Default Title'
}

In this example the prop someObject is optional, but the prop userID is required. If you fail to provide userID to MyComponent, at runtime React shows a console warning that the required prop was not provided. This warning is only shown in the development build; the production build will not log it. (React.PropTypes moved to the prop-types package in React 15.5.)

Using defaultProps allows you to simplify

const { title = 'My Default Title' } = this.props;
console.log(title);

to

console.log(this.props.title);

It’s also a safeguard for use of object array and functions. If you do not provide a default prop for an object, the following will throw an error if the prop is not passed:

if (this.props.someObject.someKey)

In the example above, this.props.someObject is undefined, so reading someKey throws and the code breaks. With defaultProps you can safely use the check above.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents