Props in React

Table of contents

No heading

No headings in the article.

In React, "props" (short for "properties") are a way for a parent component to pass data to a child component.

For eg-

//component file
import React from 'react'
import PropTypes from 'prop-types'
// shorthand for the above line-impt 

function Greeting(props){
  return (
         return <h1>Hello, {props.name}!</h1>;
   )
}

export default Greeting
//app.js file
import './App.css';
import Greeting from './components/Greeting';

function App() {
  return (
    <>
      <Greeting name="Eliza"/>
    </>
  );
}

export default App;

//Output-
Hello Eliza

in this example, the App component is using Greeting component and passing a prop "name" with value "Eliza" to it, which will be rendered in the Greeting component as "Hello Eliza"

Props are a very powerful feature of React, and they are used extensively in many real-world applications to pass data between components and customize the behaviour of child components.

--> Proptypes

propTypes is a way to define the expected types of props that a React component should receive. By defining propTypes for a component, you can catch potential bugs early on, as React will give a warning if the component is provided with a prop that doesn't match the expected type.

Here's an example of how to define propTypes for a component-

import React from 'react';
import PropTypes from 'prop-types';

function Greeting(props){
    return <h1>Hello, {props.name}!</h1>;
}

Greeting.propTypes = {
  name: PropTypes.string.isRequired
};

Greeting.defaultProps = {
    name: 'Enter you Name',
}
import './App.css';
import Greeting from './components/Greeting';

function App() {
  return (
    <>
      <Greeting name="Jia"  />
    </>
  );
}
export default App;

//Output-
Hello, Jia!

In this example, the Greeting component expects to receive a prop called name of type string, and it's isRequired, which means it must be provided.

Note-To use propTypes you must need to import this and the shorthand for the same is "impt" i.e..,

import PropTypes from 'prop-types'

React provides several built-in prop types that you can use, such as string, number, bool, func, and object. You can also use PropTypes.array, PropTypes.shape and PropTypes.oneOfType to define more complex prop types.

Using propTypes is optional, but it's a best practice to use it as it helps to catch bugs early on.

defaultProps is a way to specify default values for props that a component expects to receive, in case they are not provided by the parent component.