Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React warning: Functions are not valid as a React child

I have this react component. This is not rendering properly but getting an annoying warning like

Functions are not valid as a React child. This may happen if you return a Component instead of from the render. Or maybe you meant to call this function rather than return it.

Here's my component. What am I doing wrong here?

import React, { Component } from 'react';

class Squares extends Component {   

    constructor(props){
        super(props);
        this.createSquare = this.createSquare.bind(this);
    }

    createSquare() {
        let indents = [], rows = this.props.rows, cols = this.props.cols;
        let squareSize = 50;
        for (let i = 0; i < rows; i++) {
            for (let j = 0; i < cols; j++) {
                let topPosition = j * squareSize;
                let leftPosition = i * squareSize;
                let divStyle = {
                    top: topPosition+'px', 
                    left: leftPosition+'px'
                };
                indents.push(<div style={divStyle}></div>);
            }   
          }
        return indents;
    }    

    render() {
      return (
        <div>
            {this.createSquare()}
        </div>
      );
    }
}

export default Squares;

UPDATE

@Ross Allen - After making that change, the render method seems to be in infinite loop with potential memory crash

like image 529
Arindam Sahu Avatar asked Jul 07 '18 05:07

Arindam Sahu


2 Answers

React uses JSX to render HTML and return function within render() should contain only HTML elements and any expression that needed to be evaluated must be within { } as explanied in https://reactjs.org/docs/introducing-jsx.html. But the best practice would be to do any operation outside return just inside render() where you can store the values and refer them in the return() and restrict usage of { } to just simple expression evaluation. Refer for In depth JSX integration with React https://reactjs.org/docs/jsx-in-depth.html

render() {
var sq = this.createSquare();
return (
  <div>
    {sq}
  </div>
);

Ross Allen's answer is also fine , the point is Inside JSX enclose any operation / evaluation inside { }

like image 166
uk2797 Avatar answered Oct 26 '22 10:10

uk2797


You need to call createSquare, right now you're just passing a reference to the function. Add parentheses after it:

render() {
  return (
    <div>
      {this.createSquare()}
    </div>
  );
}
like image 36
Ross Allen Avatar answered Oct 26 '22 11:10

Ross Allen