10- Adding default props and props-types in Navbar

 

Adding default props and props-types in Navbar

Let us consider that while setting the values of props in App.js there are two certain possiblities:

Case 1 You have given wrong data type to props

  For example - In our project we wanted to give a string in {props.title} but we send integer instead of a String-- No warning

 but we want to get a warning 


Case 2-  We did not set the value of props in App.js inside return


<Navbar mode={Mode} mode1={Mode1} ToggleMode={toggleMode} />

Here we have not set values of title and about.

So it will go empty values in our front end


The best part of React JS is both the cases will find a way to run if syntax are correct

But we still need to manage props when these cases arise


For Handling Case 1:

prop-types are introduced , They perform checks whether the value written satisfies the validation or not . If not warning will be generated.


For Handling Case 2:

default props are introduced , They give default values if no value is given.

If any value is given then that value takes place instead of default value.



src --> components --> Navbar.js

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


export default function Navbar(props) {
  return (

      <nav className={`navbar navbar-expand-lg navbar-${props.mode} bg-${props.mode}`}>
  <div className="container-fluid">
   
    <a className="navbar-brand"to="/"> {props.title} </a>
   
    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span className="navbar-toggler-icon"></span>
    </button>
    <div className="collapse navbar-collapse" id="navbarSupportedContent">
      <ul className="navbar-nav me-auto mb-2 mb-lg-0">
        <li className="nav-item">
         
          <a className="nav-link " aria-current="page" to="/">Home</a>

        </li>
        <li className="nav-item">
         
          <a className="nav-link" to="/about"> {props.about} </a>
 </li>
       
   
      </ul>
      <div className="form-check form-switch">
  <input className="form-check-input"onClick={props.ToggleMode} type="checkbox"role="switch" id="flexSwitchCheckDefault"/>
  <label className={`form-check-label text-${props.mode1} htmlFor="flexSwitchCheckDefault"`}>Enable Dark Mode</label>
</div>
   
    </div>
  </div>
</nav>

   
   
  )
}

// To check wheter the value put satisfies your commands or not
  Navbar.propTypes = {
    title:  propTypes.string.isRequired,
    about: propTypes.string
  }


 // To set default value when no value is given
 Navbar.defaultProps = {
  title:"Title Here",
   about:'About Here'
 };






Comments