Props are inputs to components. They are single values or objects containing a set of values that are passed to components on creation similar to HTML-tag attributes. Here, the data is passed down from a parent component to a child component.
The primary purpose of props in React is to provide following component functionality:
- Pass custom data to your component.
- Trigger state changes.
- Use via
this.props.reactProp inside component's render() method.
For example, let us create an element with reactProp property:
<Element reactProp={"1"} />
This reactProp (or whatever you came up with) attribute name then becomes a property attached to React's native props object which originally already exists on all components created using React library.
props.reactProp;
For example, the usage of props in function component looks like below:
import React from "react";
import ReactDOM from "react-dom";
const ChildComponent = (props) => {
return (
);
};
const ParentComponent = () => {
return (
<ChildComponent name="John" age="30" gender="male" />
<ChildComponent name="Mary" age="25" geneder="female" />
);
};
The properties from props object can be accessed directly using destructing feature from ES6 (ECMAScript 2015). It is also possible to fallback to default value when the prop value is not specified. The above child component can be simplified like below.
const ChildComponent = ({ name, age, gender = "male" }) => {
return (
);
};
Note: The default value won't be used if you pass null or 0 value. i.e, default value is only used if the prop value is missed or undefined value has been passed.
See Class
The Props accessed in Class Based Component as below
import React from "react";
import ReactDOM from "react-dom";
class ChildComponent extends React.Component {
render() {
return (
);
}
}
class ParentComponent extends React.Component {
render() {
return (
<ChildComponent name="John" age="30" gender="male" />
<ChildComponent name="Mary" age="25" gender="female" />
);
}
}