reactjs – Components – Props

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 the React engine will show a console warning you that the required prop was not provided. Beware though, this warning is only shown in the development version of the React library, the production version will not log any warnings.

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 example above, this.props.someObject is undefined and therefore the check of someKey will throw an error and the code will break. With the use of defaultProps you can safely use the above check.

if you want to reproduce, please indicate the source:
reactjs – Components – Props - CodeDay