React Props
The main difference between state and props is that props are immutable, while state can change based on user interactions. This is why some container components need to define state to update and modify data. Child components, however, can only pass data through props.
Using Props
The following example demonstrates how to use props in a component:
React Example
function HelloMessage(props) {
return <h1>Hello {props.name}!</h1>;
}
const element = <HelloMessage name="tutorialpro"/>;
ReactDOM.render(
element,
document.getElementById('example')
);
In this example, the name attribute is accessed via props.name.
Default Props
You can set default values for props by using the defaultProps property of the component class, as shown in the following example:
React Example
class HelloMessage extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
HelloMessage.defaultProps = {
name: 'tutorialpro'
};
const element = <HelloMessage/>;
ReactDOM.render(
element,
document.getElementById('example')
);
State and Props
The following example demonstrates how to combine the use of state and props in an application. We can set the state in the parent component and pass it down to child components via props. In the render function, we set name and site to retrieve data passed from the parent component.
React Example
class WebSite extends React.Component {
constructor() {
super();
this.state = {
name: "tutorialpro.org",
site: "https://www.tutorialpro.org"
}
}
render() {
return (
<div>
<Name name={this.state.name} />
<Link site={this.state.site} />
</div>
);
}
}
class Name extends React.Component {
render() {
return (
<h1>{this.props.name}</h1>
);
}
}
class Link extends React.Component {
render() {
return (
<a href={this.props.site}>
{this.props.site}
</a>
);
}
}
ReactDOM.render(
<WebSite />,
document.getElementById('example')
);
Props Validation
React.PropTypes has been moved to the prop-types library after React v15.5.
<script src="https://cdn.bootcss.com/prop-types/15.6.1/prop-types.js"></script>
Props validation uses propTypes, ensuring that our application components are used correctly. React.PropTypes provides many validators to verify the validity of the data passed in. When invalid data is passed to props, a warning is thrown in the JavaScript console.
The following example creates a MyTitle component where the title property is required and must be a string; non-string types will be automatically converted to strings:
React 16.4 Example
var title = "tutorialpro.org";
// var title = 123;
class MyTitle extends React.Component {
render() {
return (
<h1>Hello, {this.props.title}</h1> ); } }
MyTitle.propTypes = { title: PropTypes.string }; ReactDOM.render( <MyTitle title={title} />, document.getElementById('example') );
## React 15.4 Example
var title = "tutorialpro.org"; // var title = 123; var MyTitle = React.createClass({ propTypes: { title: React.PropTypes.string.isRequired, },
render: function() { return <h1> {this.props.title} </h1>; } }); ReactDOM.render( <MyTitle title={title} />, document.getElementById('example') );
More validator descriptions are as follows:
MyComponent.propTypes = { // You can declare that a prop is a specific JS primitive. By default, these are all optional. optionalArray: React.PropTypes.array, optionalBool: React.PropTypes.bool, optionalFunc: React.PropTypes.func, optionalNumber: React.PropTypes.number, optionalObject: React.PropTypes.object, optionalString: React.PropTypes.string,
// Anything that can be rendered: numbers, strings, elements or an array
optionalNode: React.PropTypes.node,
// A React element
optionalElement: React.PropTypes.element,
// You can also declare that a prop is an instance of a class, using JS's instanceof operator.
optionalMessage: React.PropTypes.instanceOf(Message),
// You can ensure that your prop is limited to specific values by treating it as an enum.
optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
// A prop can be one of many types
optionalUnion: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
React.PropTypes.instanceOf(Message)
]),
// An array of a certain type
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
// An object with property values of a certain type
optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
// An object taking on a particular shape
optionalObjectWithShape: React.PropTypes.shape({
color: React.PropTypes.string,
fontSize: React.PropTypes.number
}),
// You can chain any of the above with `isRequired` to make sure a warning is shown if the prop isn't provided.
requiredFunc: React.PropTypes.func.isRequired,
// A value of any data type
requiredAny: React.PropTypes.any.isRequired,
// Custom validator. If the validation fails, it should return an Error object. Do not use `console.warn` or throw an exception, as `oneOfType` will not work with that.
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) { return new Error('Validation failed!'); } ```