Using proptypes in React.js

React JSJavascript LibraryFront End Technology

Use of proptypes ensures the type safety of receiving props on the components and also helps in making correct calculation.

Example − If we are receiving name as string and age as number then it should be received with the same type. If we receive age in string then it can result into incorrect calculation.

To use proptypes we have to install below package.

npm install –save prop-types

This package is provided by React Team. To use it on component, we will import it first

import PropType from ‘prop-types’;

we can use it on any type of component (Stateful or stateless).

At the end of component before exporting it we write it as −

Note the propType on name of component as shown above.

With the JavaScript object we are specifying the name of prop and its valid data type. If we pass an incorrect data type we will receive a warning in browser console.

The available prop types are −

  • any => it can be of any type
  • Boolean
  • String
  • Number
  • func => means function
  • array
  • object
  • symbol

Showing a warning message in browser console if there is a mismatch in prop type will help the developer correct its mistake.

Though we can use the proptype on every component, but should be used if the component is going to be used by other developers and there is considerable use of data types.

Using Ref

We can manipulate the dom element by getting hold on to it using ref.

<input value={}
we can use it on componentDidMount

The alternate latest approach to use Ref

Inside constructor we can create a ref

We can use the created ref on input element like below −

<input value={}
ref={this.testInputRef }/>

how to access this new way in componentDidMount


We have to use the current on the ref element to make it work.

This way we can avoid the creation of anonymous function to create reference for inputs.

Creating ref in functional component using hooks

We can create ref using useRef
import React, { useRef} from ‘react’;
const myFunction=(props)=>{
   const inputRef = useRef(null);// we can give some value to ref using its constructor

We can use the ref similar like created in stateful component earlier.

Note that this ref should not be used immediately as the jsx code will not be prepared by that time.

We can use the ref element inside useEffect. the useEffect function runs after the render of jsx code so that we can sure the ref variables are attached to the actual elements and are ready to use.

These refs will be accessed like above using current keyword.;

With the creation of ref, we are keeping a mutable field in our component to handle it easily.

Note that change in ref does not trigger re-render. There is an useCallback method which can notify the changes and work asynchronously.

Published on 04-Sep-2019 14:15:43