Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React PropTypes.oneOf to specify an enum doesn't work

I have a problem to specify a property of type 'enum' in react. According to the documentation here React multiple components the following snippet should work :

position : React.PropTypes.oneOf(['rightTop','rightBottom']) 

But I get the following error

ERROR in ./app/components/mqttComponents/mqttPresence.jsx Module build failed: SyntaxError:/Users/giuseppe/Projects/sw-director/app/components/mqttComponents/mqttPresence.jsx: Unexpected token (68:36) 66 |   propTypes : { 67 |     //position: React.PropTypes.string.isRequired, > 68 |     position : React.PropTypes.oneOf(['rightTop','rightBottom']),                                            ^  69 |     showMqttClientStatus : React.PropTypes.bool.isRequired,  70 |     mqtt: React.PropTypes.object  71 |   } 

I don't realise which is the error? Maybe is something related to the new ES6 syntax ?

like image 756
Giuseppe Turturiello Avatar asked Jun 20 '16 09:06

Giuseppe Turturiello


People also ask

Are PropTypes deprecated?

PropTypes is deprecated since React 15.5. 0, use the npm module prop-types instead .

Can we use PropTypes in functional component?

In this example, we are using a class component, but the same functionality could also be applied to function components, or components created by React.memo or React.forwardRef . PropTypes exports a range of validators that can be used to make sure the data you receive is valid.

How do you use PropTypes in a functional component React?

But before using it we will have to import it as always in our app: import PropTypes from 'prop-types'; They are often used after the component ends and starts with the name of the component as shown: import React from 'react'; import { PropTypes } from "prop-types"; const Count = (props) => { return ( <> .........

Should you use PropTypes?

Props and PropTypes are important mechanisms for passing read-only attributes between React components. We can use React props, short for properties, to send data from one component to another. If a component receives the wrong type of props, it can cause bugs and unexpected errors in your app.


1 Answers

With the ES6 syntax the propTypes in React should be defined as a static property. So the only difference should be in the propTypes declaration.

static propTypes = {      position : React.PropTypes.oneOf(['rightTop','rightBottom']),      showMqttClientStatus : React.PropTypes.bool.isRequired } 
like image 60
zbrox Avatar answered Oct 16 '22 14:10

zbrox