import React from
'react'
;
import ReactDOM from
'react-dom'
;
class DemoComponent extends React.Component{
render(){
return
(
<div>
{
}
<h2>Hello {
this
.props.user}</h2>
</div>
);
}
}
ReactDOM.render(
<DemoComponent user =
"Alice"
/>,
document.getElementById(
"root"
)
);
In functional component
We dont use this.props in functional component and use props in functional component.
import React from
'react'
;
import ReactDOM from
'react-dom'
;
function
DemoComponent(props){
return
(
<div>
{
}
<h2>Hello {props.user}</h2>
</div>
);
}
ReactDOM.render(
<DemoComponent user =
"Alice"
/>,
document.getElementById(
"root"
)
);
Note: Props are read-only. We are not allowed to modify the content of a prop. Whatever the type of Component is – functional or class-based, none of them is allowed to modify their props.
Default props:
It create a object of class based on class name called as defaultProps. By default it set the value if no value is assigned. and provide the value as a props.
import React from
'react'
;
import ReactDOM from
'react-dom'
;
class ExampleClass extends React.Component{
render(){
return
(
<div>
{
}
<h1>This is {
this
.props.title} Website!</h1>
<h1>User is {
this
.props.name} </h1>
<h1>User is {
this
.props.map(function nameiter(item, i){
return (item + (i+1))
})</h1>
</div>
);
}
}
ExampleClass.defaultProps = {
title:
"Blogger",
name: ["Ashish", "Kumar"]
}
ReactDOM.render(
<ExampleClass />,
document.getElementById(
"root"
)
);
Output
This is Blogger Website !
AshishKumar
Ashish1Kumar2
Props validation
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
<h3>Array: {this.props.propArray}</h3>
<h3>Bool: {this.props.propBool ? "True..." : "False..."}</h3>
<h3>Func: {this.props.propFunc(3)}</h3>
<h3>Number: {this.props.propNumber}</h3>
<h3>String: {this.props.propString}</h3>
<h3>Object: {this.props.propObject.objectName1}</h3>
<h3>Object: {this.props.propObject.objectName2}</h3>
<h3>Object: {this.props.propObject.objectName3}</h3>
</div>
);
}
}
App.propTypes = {
propArray: React.PropTypes.array.isRequired,
propBool: React.PropTypes.bool.isRequired,
propFunc: React.PropTypes.func,
propNumber: React.PropTypes.number,
propString: React.PropTypes.string,
propObject: React.PropTypes.object
}
App.defaultProps = {
propArray: [1,2,3,4,5],
propBool: true,
propFunc: function(e){return e},
propNumber: 1,
propString: "String value...",
propObject: {
objectName1:"objectValue1",
objectName2: "objectValue2",
objectName3: "objectValue3"
}
}
export default App;
Output
Bool: true...
String: String value..