ReactJS props
Props(short form of "properties") are provided as arguments to a ReactJS component and appear exactly similar to HTML attributes of regular HTML tags. So, if we define components as custom tags in ReactJS, we can also define their attributes as props. These props can be used in our render method to render the dynamic data.
One thing to note about props is that the props are immutable or read-only (but state object is mutable).
The component receives the argument as a props object. The props can be supplied to a class-based component or function-based component. There is a minute difference in the use of props in both types of components.
Class-based props
for example,
class Panel extends React.Component { constructor(props) { super(props); } render() { return <div class="myPanel"> <img src={this.props.src} alt="no image" height={this.props.ht} width={this.props.wd} /> <br/><button> ♥ </button> </div>; } } ReactDOM.render(<Panel src="https://cdn.pixabay.com/photo/2018/02/09/21/46/rose-3142529__340.jpg" ht="200" wd="300" />, document.getElementById('root'));
In the above code src, ht and wd are processed as props in the component Panel. A prop is accessed using the props object(e.g this.props.arg). available in the component.
The result of the above code will appear as,
Function-based props
We can use props in a function-based component in the same way as they are used in class-based components.
function Note(props) { return <div class="myPanel"> <label for="ta">{props.cap}</label><br/> <textarea id="ta" rows={props.rw} cols={props.cl} placeholder="Write your feedback here"/><br/><button>submit</button></div>; } ReactDOM.render(<Note rw="10" cl="20" cap="Feedback"/>, document.getElementById('root'));
The difference is that props are passed as an argument to the function Note. The props are accessed using props.arg in the method.
The result will appear as
Passing information from parent to child component
The information can be passed from parent to child components using props, for example
class Parent extends React.Component { constructor() { super(); } render() { return <div><h2>Welcome</h2><hr/> <Child fname="Steve" lname="Smith"/> </div>; } } class Child extends Parent { constructor() { super(); } render() { return <div><h3>{this.props.fname} {this.props.lname}</h3></div>; } } ReactDOM.render(<Parent/>, document.getElementById('root'));
the result will appear as,
State vs Props
- The state is mutable but props are immutable.
- The state is available only in class-based components, props are available in both class-based and function-based components.
- The state can be/are associated with the handlers.
- The state is managed inside the component, but the props are passed into the container from the outside.