top of page
Logo der Online Agentur mdwp

PropTypes

PropTypes is a term used in React JS which denotes a feature that allows you to specify the types of properties your component needs to receive to function properly. It verifies that a property that a component is supposed to receive has the proper type. They are used in the development stage to catch bugs but they don’t affect the production code. PropTypes are used to make your code more robust and prevent potential issues, especially in bigger projects.

PropTypes can be defined in two ways:

1. Inside a class component, PropTypes can be applied as shown below:

```javascript
import React from 'react';
import PropTypes from 'prop-types';

class MyComponent extends React.Component {
render() {
const { name, age } = this.props;
return <p>{name} is {age} years old!</p>;
}
}

MyComponent.propTypes = {
name: PropTypes.string,
age: PropTypes.number,
};
```

In the example above, `MyComponent` expects `name` to be a string and `age` to be a number.

2. In a functional component, it can be applied as shown below:

```javascript
import React from 'react';
import PropTypes from 'prop-types';

const MyFunctionalComponent = ({ name, age }) => {
return <p>{name} is {age} years old!</p>;
}

MyFunctionalComponent.propTypes = {
name: PropTypes.string,
age: PropTypes.number,
};
```

In the example above, `MyFunctionalComponent` expects `name` to be a string and `age` to be a number.

In both examples, if `name` is not a string or `age` is not a number, a warning will be shown in the JavaScript console in the browser, providing you with feedback about what might have gone wrong.

bottom of page