2. React Props #

Created Sunday 06 September 2020

Why #

React components should be reusable, so there’s a need to associate data with a component, which it uses in rendering its JSX.

How #

Everything in React is a component. And the whole UI is nothing but a tree of these components.

Note: Read-only property of props does not clash with React’s philosophy of inherent coupling of final logic-expressions and UI code. The code to change props is not a final expression that is rendered. The final logic-expressions should be at-most logical operators and other short stuff.

What #

Prop, short for properties, is a component’s data storage object. All data that a component works with is stored in this one object.

How to work with props? #

Useful trick: An alternative to dot notation is to use ES6 destructuring, where the first argument can be a curly brace with props datum as comma separated objects.

Examples

// Component file
function ChildComponent = (prop_obj) => {
  return (<div>
          	<h1> {prop_obj.names} </h1>
          	<h1> {prop_obj.date} </h1>
          </div>);
}

// Parent component passing prop to child component
function ParentToChildComponent = (props) => {
  return <ChildComponent names="Names" date="27 March" />
}

If using dot notation, the child component would look like this, concise.

// Component file
function ChildComponent = ({names, date}) => {
  return (<div>
          	<h1> {names} </h1>
          	<h1> {date} </h1>
          </div>);
}

Class based component.

class Welcome extends React.Component {
 render() {
   return <h1>Hello, {this.props.name}</h1>;
 }
}