React JS
# Props Default value and Type Checking with Proptypes in React
Let's say we have a component Header
which is basically the navbar on the top of the page. It takes a prop title
which is the title of the app to be shown on the navbar.
import React, { Component } from 'react';
class Header extends Component {
render() {
const { title } = this.props;
return (
<nav className="navbar">
<div className="title">
{title}
</div>
</nav>
);
}
}
export default Header;
we can use this component after importing in our app like :
<Header title="Application One"/>
So in case the prop value is not provided in the usage we can set a default value by using defaultProps
with our component. Let's say we want to give it a default value of My App
.
import React, { Component } from 'react';
class Header extends Component {
render() {
const { title } = this.props;
return (
<nav className="navbar">
<div className="title">
{title}
</div>
</nav>
);
}
}
// default value
Header.defaultProps = {
title: 'My App'
};
export default Header;
Now we can reduce type errors for the data we pass to our components in react by validating the type using Proptypes
. So firstly we will import Proptypes
in our component.
import PropTypes from 'prop-types';
Now as we can see that the type of our title should be a string so we can use propTypes
to validate it. We can also make it a required field by adding .isRequired
to our validation.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Header extends Component {
render() {
const { title } = this.props;
return (
<nav className="navbar">
<div className="title">
{title}
</div>
</nav>
);
}
}
// default value
Header.defaultProps = {
title: 'My App'
}
// typechecking title to be string
Header.propTypes = {
title: PropTypes.string // should be string
}
// Or should be string and is mandatory
// Header.propTypes = {
// title: PropTypes.string.isRequired
// }
export default Header;
Some of the common PropTypes
are :
// Array
PropTypes.array
// Boolean
PropTypes.bool
// FUnction
PropTypes.func
// Number
PropTypes.number
// Object
PropTypes.object
// String
PropTypes.string
// Symbol
PropTypes.symbol
we can also implement type checks inside the class as:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Header extends Component {
static propTypes = {
title: PropTypes.string.isRequired
};
render() {
const { title } = this.props;
return (
<nav className="navbar">
<div className="title">
{title}
</div>
</nav>
);
}
}
Header.defaultProps = {
title: 'My App'
};
export default Header;
Learn More
- Props Default value and Type Checking with Proptypes in React