Props in React
Created on: Sep 12, 2024
React components use props to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props are objects which can be used inside a component.
Let's take a example.
import Product from "./Product"; function App() { return ( <div> <h1>Product List</h1> <Product name="Smartphone" price="699" /> <Product name="Laptop" /> </div> ); } export default App;
import React from "react"; import PropTypes from "prop-types"; function Product(props) { return ( <div> <h2>{props.name}</h2> <p>Price: ${props.price}</p> </div> ); } Product.defaultProps = { price: 999, }; Product.prototype = { name: PropTypes.string.isRequired, price: PropTypes.number, }; export default Product;
In the above code, we are passing name and price from App component to Product component using props. We have give default value for price which will be used if not supplied in props. Also we have defined the types for props which can used to validate the information we pass.
Important points for props
- Props are read-only. We are not allowed to modify the content of a prop
- We need to use
this
keyword to access props in class based component.
You can check whole in my github repo.