Home > Enterprise >  Failed prop type while doing prop validation in React.js
Failed prop type while doing prop validation in React.js

Time:12-12

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 children is invalid; it must be a function, usually from the prop-types package, but received undefined.This often happens because of typos such as PropTypes.function instead of PropTypes.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
}
  • Related