Instructions
- first you have to pass the props in the element used in App.js In what you want to use that
- In the following image I am passing the title to the Navbar component
- Then open the Navbar.js to use the props use (props) as argument in the function
- Then use props.(your property name=title in this case)
now you are good to go
Prop types
prop types wo hote hai jo aapko props ki kuch specification or usko shi se use karne k liye utility provide karte hai
Suppose if you are using the same props name _ title as a string but by mistake you pass that variable as a number then it is hard to find where the error is
then you can set the type of the props which you are using in your component
- first you have to import the proptypes from react
- then you just write as given below
code
import '../../index.css' import PropTypes from 'prop-types'; const Navbar = (props) => { return ( <div> <nav> <ul className='flex flex-row bg-black text-white py-5 space-x-5 justify-center text-center '> <li>{props.title}</li> <li>Home</li> <li>About</li> </ul> </nav> </div> ); } export default Navbar; Navbar.prototype = { title: PropTypes.string, } Navbar.defaultProps = { title: "Default Title", }
- It is showing that the type of the title is string and if you pass any wrong type like : object, number....etc then it will throw an error an you can easily find out in this component
- you can also add a required text to set that it is required to set/pass the value
default Prop type
- If you want to set some default value of the props untill and unless they got passed then you can by the following syntax
- Now if there is no other passing value for this title then the Default Title got passed