Checking data types for React component props lets us prevent many mistakes in our code.
In this article, we’ll look at how to check data types for React component props.
Use Prop Types to Check to Validate React Compoennt Prop Data
By default, React lets us pass anything from parent components to child components via props. This isn’t ideal because it’s very easy to make a mistake that may cause runtime errors in production.
Therefore, we should use React’s built-in prop-type validation feature to check the data type of props. We can also use it to check if the prop value has the format that we want them to be in.
There’s built-in prop type for common JavaScript data types. In addition, we can check for a combination of one or more types and we can also pass in a custom validation to check for the prop data.
For instance, we can use it as follows:
import React from "react";
import PropTypes from "prop-types";
const Foo = ({ data }) => {
return <p>{data}</p>;
};
Foo.propTypes = {
data: PropTypes.string
};
export default function App() {
return <Foo data="bar" />;
}
In the code above, we have:
Foo.PropTypes = {
data: PropTypes.string
};
to check that the data
prop is indeed a string. In the code above, we passed in a string as the value of the data
prop. Therefore, we should see the p element displayed with the text ‘bar’ inside.
Otherwise, we would get an error.
We can add our own prop data validation as follows:
import React from "react";
const Foo = ({ data }) => {
return <p>{data}</p>;
};
Foo.propTypes = {
data(props, propName, componentName) {
if (!/bar/.test(props[propName])) {
return new Error("I want bar");
}
}
};
export default function App() {
return <Foo data="baz" />;
}
In the code above, we have:
Foo.propTypes = {
data(props, propName, componentName) {
if (!/bar/.test(props[propName])) {
return new Error("I want bar");
}
}
};
Therefore, if we didn’t pass in 'bar'
as the value of the data
prop into Foo
, we’ll get the error ‘I want bar’ logged in the console. We pass in 'baz'
, so we’ll get the error.
Conclusion
By default, React lets us pass anything from parent components to child components via props. This isn’t ideal because it’s very easy to make a mistake that may cause runtime errors in production.
Therefore, we should use React’s built-in prop-type validation feature to check the data type of props. We can also use it to check if the prop value has the format that we want them to be in.