Props in React.js

React props

React allows components to communicate using props, which stands for properties. It is an object which passes data from parent component to child component. Props are immutable so we cannot modify props inside the component. Let's understand props by an example. To follow along, edit App.js file with the following code.

App.js

import BlogList from './components/BlogList.js';

function App() {
  return (
    <>
      <BlogList title="Blog List" />      
    </>
  );
}

export default App;

We have BlogList Component inside src/components folder.

BlogList.js

const BlogList = (props) => {
  return (
    <>
      <h1>{props.heading}</h1>
      <h3>{props.title}</h3>
    </>
  );
}

export default BlogList;

Here we are passing heading and title as a prop from App component which is the parent component to its child component which is BlogList Component.

We can also destructure props in the following way:

const BlogList = ({title, heading}) => {
  return (
    <>
      <h1>{heading}</h1>
      <h3>{title}</h3>
    </>
  );
}

export default BlogList;

PropTypes

PropTypes are used to make sure the values passed through props are valid. PropTypes includes props and their respective PropTypes for type checking. The main benefit of type checking is that it makes the code base more robust and bug free.

At first we need to import PropTypes from 'prop-types'. So let's import it in App.js file

import PropTypes from 'prop-types';

Then, we can add type checking for the props like below.

BlogList.propTypes = {
  title: PropTypes.string
}

If we pass the integer value for props title, it will throw a warning on console. We can check it by adding following line of code in App.js file:

function App() {
  return (
    <>
      <BlogList title={30} heading= "List of Blogs"/>      
    </>
  );
}

Now, if we see the console, there will be a warning message . Hence, it is recommended to do type checking on our application .

So, the final App.js file will look like this:

import BlogList from './components/BlogList.js';
import PropTypes from 'prop-types';

function App() {
  return (
    <>
      <BlogList title="Blog List" heading= "List of Blogs"/>      
    </>
  );
}

BlogList.propTypes = {
  title: PropTypes.string
}
export default App;

That was all about props and PropTypes in React. Lets get connected on twitter. Twitter. Happy Reading !