I have a following loading component which is an HOC
import React, { Component } from "react";
const isEmpty = prop =>
prop === null ||
prop === undefined ||
(prop.hasOwnProperty("length") && prop.length === 0) ||
(prop.constructor === Object && Object.keys(prop).length === 0);
const LoadingHOC = loadingProp => WrappedComponent => {
return class LoadingHOC extends Component {
componentDidMount() {
this.startTimer = Date.now();
}
componentWillUpdate(nextProps) {
if (!isEmpty(nextProps[loadingProp])) {
this.endTimer = Date.now();
}
}
render() {
const myProps = {
loadingTime: ((this.endTimer - this.startTimer) / 1000).toFixed(2)
};
return isEmpty(this.props[loadingProp]) ? (
<div className="loader" />
) : (
<WrappedComponent {...this.props} {...myProps} />
);
}
};
};
export default LoadingHOC;
I'm using this in my Feed component to have a loading effect.
Feed component is:
import React, { Component } from "react";
import FeedItem from "./FeedItem";
import LoadingHOC from "./HOC/LoadingHOC";
class Feed extends Component {
state = {
filterText: ""
};
render() {
const { loadingTime } = this.props;
return (
<div className="feed">
<FeedItem
contacts={this.props.contacts}
filterText={this.state.filterText}
/>
{/* <p>Loading time {loadingTime} seconds</p> */}
</div>
);
}
}
export default LoadingHOC("contacts", Feed);
I'm using the Feed component in my App.js like <Feed contacts={this.state.contacts} /> this.
However I get the following error - Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
I understand that this is because the HOC is not being called correctly. But what am I doing wrong in export default LoadingHOC("contacts", Feed); ?
Your HOC is a curried function. So you need to call twice
export default LoadingHOC("contacts")(Feed);
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