I'm working on a React project, in which there is a context under the name of CurrencyContext.js. The whole project is running perfectly, however, I'm getting a console error that says Failed prop type.
Full error message
Warning: Failed prop type: CurrencyContextProvider: prop type
childrenis invalid; it must be a function, usually from theprop-typespackage, but receivedundefined.This often happens because of typos such asPropTypes.functioninstead ofPropTypes.func.
For more clarifications here is the code of CurrencyContext.js. Please let me know if something is not clear enough.
import React, {Component, createContext} from "react"
export const CurrencyContext = createContext()
class CurrencyContextProvider extends Component {
constructor(props) {
super(props);
this.state = {
selectedCurrency: 'USD'
}
}
setCurrency(c){
this.setState({selectedCurrency: c})
}
render() {
return (
<CurrencyContext.Provider value={{...this.state, setCurrency: this.setCurrency.bind(this)}}>
{this.props.children}
</CurrencyContext.Provider>
)
}
}
CurrencyContextProvider.propTypes = {
children: React.ReactNode
}
export default CurrencyContextProvider;
CodePudding user response:
React.ReactNode is undefined in javascript. If you're using typescript it would be a type, but even that only exists at compile time and cannot be used for propTypes.
Instead, the way to do the children prop type is:
import PropTypes from 'prop-types';
// ...
CurrencyContextProvider.propTypes = {
children: PropTypes.node
}
