CodesJava

Easy learning with example program codes

Props in ReactJS

React Props
Props or “Properties” are read-only components, that gives a way to pass data from one component to other components. It stores the value of attributes of a tag. It is an immutable object that works similarly to the HTML attributes. The props cannot be modified from inside the component as they are immutable. But we can add attributes called props, inside the components. The props are thus used to add immutable data in the component. The props are used inside the component but are added to the reactDom.render() method in the main.js file.

Example:
App.js:

import React, { Component } from 'react';  
class App extends React.Component {  
render() {     
return (  
<div>  
<h2> Hello { this.props.msg } </h2>    
<p> Have a Great day. </p>          
</div>  
);  
}  
}  
export default App;

Main.js:

import React from 'react';  
import ReactDOM from 'react-dom';  
import App from './App.js';  
ReactDOM.render(<App msg = "World!" />, document.getElementById('app'));

Output:

Hello World!
Have a Great day.

Default Props:
We can also set default props directly on the component constructor.

Example:
App.js:

import React, { Component } from 'react';  
class App extends React.Component {  
render() {     
return (  
<div>  
<h2> Hello { this.props.msg } </h2>    
<p> Have a Great day. </p>          
</div>  
);  
}  
}  
App.defaultProps = {  
msg: "World!"  
}  
export default App;

Main.js:

import React from 'react';  
import ReactDOM from 'react-dom';  
import App from './App.js';  
ReactDOM.render(<App/>, document.getElementById('app'));

Output:

Hello World!
Have a Great day.

Combining State and Props Example:

import React, { Component } from 'react';  
class App extends React.Component {  
constructor() {  
super();  
this.state = {  
data:   
[  {             
"name":"Dhoni"             
},  
{            
"name":"Kohli"             
},  
{    
"name":"Pandya"          
}  ]  
}  
}  
render() {  
return (  
<div>  
<PLAYERname/>  
<ul>            
{this.state.data.map((item) => <List data = {item} />)}           
</ul>  
</div>  
);  
}  
}  
class PLAYERname extends React.Component {  
render() {  
return (  
<div>  
<h1>Player Names</h1>  
</div>  
);  
}  
}  
class List extends React.Component {  
render() {  
return (  
<ul>            
<li>{this.props.data.name}</li>   
</ul>  
);  
}  
}  
export default App;

Output:

Player Names
      ●	Dhoni
      ●	Kohli
      ●	Pandya
Please follow and like us:
error









Copyright © 2019 CodesJava DMCA.com Protection Status