React Props

Page content:
1.Props-Introduction
2.Props-Example
3.Props-Default Props
4.Props-State with Props

1.Introduction:

1.Props stands for properties.
2.React props are read-only ,i.e we can’t changes them directly.
3.props gives the way to pass data from one component to another.
4.Inside the components, we can add attributes called props.
5.These attributes are available in the component as this.props and can be used to render dynamic data in our render method.


2.Example:

App.jsx:

import React, { Component } from 'react';  
  class App extends React.Component {  
   render() {     
      return (  
          <div>  
            <h1> Welcome to { this.props.name } </h1>    
          </div>  
      );  
   }  
}  
export default App;


main.js:

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


Here name attribute is passed to the App component which can be accessed inside using this.props.name.


3.Default Props:

1.It is not necessary to always add props in the reactDOM.render() element.
2.You can also set default props directly on the component constructor.

App.jsx

import React, { Component } from 'react';  
class App extends React.Component {  
   render() {     
      return (  
          <div>  
            <p>Default Props Example</p>  
            <h3>Welcome to {this.props.name}</h3>   
            </div>  
        );  
    }  
}  
App.defaultProps = {  
   name: "webdev99"  
}  
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'));




4.State with props:

we can combine state with props. let us set the state in the parent component and pass it to the child component as props & access it inside the child component.
let’s understand the below code:

App.jsx:

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
	     name:"welcome to webdev99",
         data: "my data for state"
      }
   }
   render() {
      return (
         <div>
		    <Header myheaderProp = {this.state.name}/>
            <Data mydataProp = {this.state.data}/>
         </div>
      );
   }
}
class Header extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.myheaderProp}</h1>
         </div>
      );
   }
}
class Data extends React.Component {
   render() {
      return (
         <div>
            <h2>{this.props.mydataProp}</h2>
         </div>
      );
   }
}
export default App;


main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));