React Props Basics

React allows us to pass information to a Component using something called props (stands for properties). Whether you declare a component as a function or a class, it must never modify its own props. Consider this sum function:

function sum(a, b) {

return a + b;

}

Such functions are called “pure” because they do not attempt to change their inputs, and always return the same result for the same inputs. In contrast, this function is impure because it changes its own input:

function withdraw(account, amount) {

account.total -= amount;

}

React is pretty flexible but it has a single strict rule: All React components must act like pure functions with respect to their props. Of course, application UIs are dynamic and change over time

Passing and Accessing props

We can pass props to any component as we declare attributes for any HTML tag. Have a look at the below code snippet:

<DemoComponent sampleProp = “HelloProp” />

In the above code snippet, we are passing a prop named sampleProp to the component named DemoComponent. This prop has a value “HelloProp”. Let us now see how can we access these props. We can access any props inside from the component’s class to which the props is passed. The props can be accessed as

this.props.propName;

We can access any prop from inside a component’s class using the above syntax. The ‘this.props’ is a kind of global object which stores all of a components props. The propName, that is the names of props are keys of this object.

Below is a sample program to illustrate how to pass and access props from a component:

import React from ‘react’;

import ReactDOM from ‘react-dom’;

// sample component to illustrate props

class DemoComponent extends React.Component{

render(){

return(

<div>

{/*accessing information from props */}

<h2>Hello {this.props.user}</h2>

<h3>Welcome </h3>

</div>

);

}

}

ReactDOM.render(

// passing props

<DemoComponent user = “User 1l” />,

document.getElementById(“root”)

);

Share this post
[social_warfare]
ReactJS Props
Using Props

Get industry recognized certification – Contact us

keyboard_arrow_up