React Props

Props is a special keyword in React that stands for properties and is used for passing data from one component to another

In  React component-based library , The user interface is broken down into small, reusable components. Sometimes it's necessary for those parts to talk to each other or exchange data, and props are a great method to do so. 

The data provided by the parent component should not be modified by the child components because props data is read-only. 

How to use Props in React

  • Specify an attribute and its corresponding value (data). 
    • Sstablish our own properties and allocate data using interpolation { }
  • Pass it to the child component(s) via properties. 
    • Transmitting properties is really straightforward. Similar to how arguments are passed to a function, props are transmitted into a React component, providing all requisite data. Arguments provided to a function:
  • Present the properties data. 

 

With Example:

  • Defining a name attribute for the ChildComponent and assigning it the string value: "my name is Deepak" 
    • <ChildComponent name ={“my name is Deepak”} />
  • Let us transmit the "my name is Deepak" string via props. 
    • const ChildComponent = (props) => { … };
  • Rendering Props Data in Child Component
    • const ChildComponent = (props) => { return <p>{props.name}</p>;   }


Data with props are passed in a unidirectional flow from parent to child.


We can render multiple child's inside the parent content passing different values 

class ParentComponent extends Component {    

render() {   

return (      

<h1>        parent component.        

           <ChildComponent text={"my name is Deepak"} />        

           <ChildComponent text={"my name is Ram"} />       

          <ChildComponent text={"my name is Rajesh"} />      

 </h1>   

 );  } }

Each child component renders its own prop data. This is how you can utilise props to pass data and transform static components into dynamic ones.

 

To sum up:

  • React's props keyword represents properties.
  • Components receive props like function arguments.
  • Props can only be sent parent-to-child to components.
  • Props data is read-only.

 

Author
Full Stack Developer

Deepak Talwar

Technical Architect & Full Stack Developer with 18+ years of Professional Experience in Microsoft Technologies & PHP Platform. Hands on experience with C#, VB, ASP.NET, ASP.NET MVC, ASP.NET Core, ASP.NET Web API, Linq, ADO.NET, Entity Framework, Entity Framework Core, Sql Server, MYSQL, NoSql, Javascript, Angular, jQuery, AWS, Azure, React, Angular, Laravel, Codeingiter, Serenity, VBA, Cloud Computing, Microservices, Design Patterns, Software Architecture, Web Design and Development.

Related Post