Understanding components and props in React.js

React applications are made up of components. Component are generally uses react elements. Components can be independent, reusable pieces.

There are two types of components −

  • Stateless component ( Basically JavaScript functions )
  • Stateful component ( Uses JavaScript class feature )

Both the components types receives a proprieties object generally called as props.

Stateless component has a return statement in function and Stateful component has a render method which returns react elements.

Simple react element to display on the page is −

const message=<h1>Hello</h1>;
ReactDOM.render( message, document.getElementById(‘root’) );

It displays the Hello message on the screen.

Creating a functional component −

function Message(props){
   return (
      <h1> {props.message} </h1>

The above JavaScript function is accepting a single properties object named as props. The props object contains the message.

Creating class bases Stateful component:
class Message extends React.component{
      return (
         <h1>{this.props.message} </h1>

The above two components are equal in functionality. The class based component has additional lifecycle features.

Rendering the components

React elements can hold the simple html tags. example −

const player =<h2> Steve </h2>;

similarly, react elements can hold the functional or class based component −

const message=<Message message=”hello”/>;

The attributes passed on the component can be accessed as props object properties. The props object will look like −

{ message: Hello}

The name of the component must be in capital letter so that React will able to differentiate it between html element or user defined element.

Composing multiple component

Components can be used in the other components or nesting of components is possible. We can create the smallest function component or using abstraction level is useful.

The props are read only in nature and should not be modified inside component.

Components are called as pure if they return same output for same input at any point of time.

Example of pure component 

function Multiplication(i, j){
   return i*j;