2

I am trying to declare and return multiple HOC's from any array, but keep being returned a "Functions are not valid as a React child." Error. Has anyone ran into this issue before?

JS:

....

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};

const withRequestAnimationFrame = () => WrappedComponent => {
  class RequestAnimationFrame extends Component {
    state = {
      timeStamp: 0,
      newItem: "Test"
    };

    componentDidMount() {
      const min = 1;
      const max = 100;
      const rand = Math.floor(Math.random() * (max - min + 1)) + min;
      this.setState({ timeStamp: this.state.timeStamp + rand });
    }

    render() {
      return (
        <WrappedComponent {...this.state} {...this.props} />
      )
    }
  }
  return RequestAnimationFrame;
};

const App = ({ timeStamp, newItem }) => (
  <div style={styles}>
    <h1>{timeStamp}</h1>
    <p>{newItem}</p>
  </div>
);

const arrayItems = ["EnhancedApp", "EnhancedApp2"];
const Products = ({ items }) => {
  return (
    items.map((item, index)  => (
      item = withRequestAnimationFrame()(App)
    ))
  )
};

function Product() {
  return (
    <div>
      <Products items={arrayItems} />
    </div>
  )
}

render(<Product />, document.getElementById("root"));

1 Answer 1

1
  1. This line is the problem:

    item = withRequestAnimationFrame()(App)
    

    What your doing there is assigning result of withRequestAnimationFrame()(App) function to item which is definetly not what you wanted. I assume you wanted to render there multiple instances of withRequestAnimationFrame component. You can do it like this:

    items.map((item, index)  => (
        const NewComponent = withRequestAnimationFrame(item)(App);
        return <NewComponent key={index}/>
    ))
    
  2. Second problem is that you are not passing item prop to the wrapped component. To pass item prop you should do:

    const withRequestAnimationFrame = (item) => WrappedComponent => {
       class RequestAnimationFrame extends React.Component {
           state = {
               timeStamp: 0,
               newItem: item
           };
    
Sign up to request clarification or add additional context in comments.

2 Comments

No Dice! "const arrayItems = ["EnhancedApp", "EnhancedApp2"]; const Products = ({ items }) => { return items.map(item => { return withRequestAnimationFrame(item)(App) }) };"
Yea, I just wanted a new instance. "newItem" was just a placeholder but good looking out. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.