React Props

React Props

A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute value of a tag, and its work is similar to the HTML elements. It helps to pass data from one component to another components. Props are like function arguments, as props are passed to the component in a similar way as arguments passed in the function.

We cannot modify the props inside the component. We can add attributes called props inside the components. These attributes are available in the component as this.props and use for rendering the dynamic data in our render method.

When you require immutable data in the component, you need to add the reactDom.render() method in the  main.js file of the ReactJS project and use that file inside the component in which you need it.

For example:

App.js

import React, { Component } from 'react'; 
class App extends React.Component { 
render() { 
return ( 

Hello { this.props.name }

This is tutorialandexample.com website which provides you lot of tutorials

); } } export default App;

Main.js

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

Output:

Hello world React props

Default Props

It is not mandatory to always add props in the reactDom.render() element. You can also set default props directly on the component constructor. It is clearly explained in the following example:

Example:

import React, { Component } from 'react'; 
class App extends React.Component { 
render() {
return ( 

Hello World

Default Pros Example

Welcome to {this.props.name}

tutorialandexample.com provides you one of the best tutorials.

); } } App.defaultProps = { name: "tutorialandexample.com" } export default App;

Main.js

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

Output:

Default props

State and Props

State and props both can be combined in the app. You can set the state in the parent component and pass it to the child component using props.

For example:

App.js

import React, { Component } from 'react'; 
class App extends React.Component { 
constructor(props) { 
super(props); 
this.state = { 
name: "tutorialandexample.com", 
} 
} 
render() {  
return ( 
); } } class Tutorial extends React.Component { render() { return (

State & Props Example

Welcome to {this.props.tutorialProp}

tutorialandexample.com provides you one of the best tutorials.

); } } export default App;

Main.js

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

Output:

States and Props



ADVERTISEMENT
ADVERTISEMENT