I'm trying to have single PropTypes definition to reuse it in several components, and have issues with that. I define the static propTypes in separate class and then import it as module. Say, I have React component of a view:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ExampleType from './example-type.js';
class MyComponent extends Component {
static propTypes = {
...ExampleType.propTypes, // <--- note here, that's how I'm trying to make it work
// and the line below duplicates same field from ExampleType.propTypes,
// this is needed because otherwise Linter throws an error
// that PropTypes is defined, but never used:
instanceName: PropTypes.string
}
static defaultProps = {
...ExampleType.defaultProps
}
render() {
return (
<div>
<h3>{this.props.instanceName}</h3>
<p>
{this.props.instanceValue}
</p>
</div>
)
}
}
example-type.js is that:
import PropTypes from 'prop-types';
class ExampleType {
static propTypes = {
instanceName: PropTypes.string,
instanceValue: PropTypes.string
}
static defaultProps = {
instanceName: '',
instanceValue: ''
}
}
export default ExampleType;
And doing this way, PropTypes check does not happen. If I change defaultProps definition to that without spread operator:
static propTypes = {
// ...ExampleType.propTypes, // and now without spread ...
instanceName: PropTypes.string,
instanceValue: PropTypes.string
}
Than it works as expected.
Well, I know that reusing of single property types definition is available in different ways like here https://stackoverflow.com/a/37720537/2335174 , but I'm curios why my variant with spread operator does not work. MyComponent.propTypes object looks the same in debugger in both cases, with and without spread.
Am I doing something wrong?
It seems to work for me, see here: https://codesandbox.io/s/jlll2zm6xv
Have you included the transform-object-rest-spread plugin in your Babel setup?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With