React props, prop-types and default props

October 01, 2020

Access your props in jsx

To access props in jsx use this.props in your class based component:

export class NavBar extends Component {
  render() {
    return (
      <div>
        <nav className="navbar bg-primary">
          <i className={this.props.icon} />{this.props.title}
          </nav>
      </div>
    )
  }
}

To pass props to your component:

      <Fragment>
        <NavBar title='Home' icon='fab fa-home' />
      </Fragment>

With the proper css in place this will look like something like this:

Home png

Default props make sure that there are props initialiezed, even though no props were passed to the component.
If you are still using class based components, the default props declaration is like:

export class NavBar extends Component {
  static defaultProps = {
    title: "Home",
    icon: "fas fa-home"
  }
  ...

Additionally, we can put in place contraints, or checks for props validity. Let us make sure that the our props conform the data types we require and they are really passed in (required props).

import React, { Component } from 'react'
import PropTypes from 'prop-types'

export class NavBar extends Component {
  static propTypes = {
    title: PropTypes.string.isRequired,
    icon: PropTypes.string.isRequired
  }

There are 2 things to look out for:

  • import PropTypes from ‘prop-types’
  • declaration of static propTypes

Default props and PropTypes in React functional components

Instead of using class components, most of us tends to use functional components. How do we use default props and proptypes in react functional compnents? The below example will demonstrate that:

import PropTypes from "prop-types"
import React from "react"

const NavBar = ({ title, icon }) => (
  <div>
    <nav className='navbar bg-primary'>
      <i className={icon} />
      {title}
    </nav>
  </div>
)

NavBar.defaultProps = {
  title: "Home",
  icon: "fas fa-home",
}

NavBar.propTypes = {
  title: PropTypes.string.isRequired,
  icon: PropTypes.string.isRequired,
}

export default NavBar

However, this is again obsolete, let’s refactor that as defaultProps are better removed and replaced with default parameter values in props descructuring, as follows:

import PropTypes from "prop-types"
import React from "react"

const NavBar = ({ title = "Home", icon = "fas fa-home" }) => (
  <div>
    <nav className='navbar bg-primary'>
      <i className={icon} />
      {title}
    </nav>
  </div>
)

NavBar.propTypes = {
  title: PropTypes.string.isRequired,
  icon: PropTypes.string.isRequired,
}

export default NavBar

It’s now a lot cleaner and leaner. emoji-thumbsup