0

I tried rendering gridWithNode function inside render which is not working and I am getting this error: Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it. at div at Pathfind (http://localhost:3000/static/js/bundle.js:185:74) at div at App

my code looks like this in Pathfind.js

import React, { useState, useEffect } from "react";
import Node from './Node';
import './Pathfind.css';

const rows = 5;
const cols = 5;

const Pathfind = () => {
const [Grid, setGrid] = useState([]);

useEffect(() => {
    initializeGrid();
}, []);

// CREATES THE GRID
const initializeGrid = () => {
    const grid = new Array(cols);

    for (let i = 0; i < cols; i++) {
        grid[i] = new Array(rows);
    }
    createSpot(grid);

    setGrid(grid);
}

// CREATES THE SPOT 
const createSpot = (grid) => {
    for (let i = 0; i < cols; i++) {
        for (let j = 0; j < rows; j++) {
            grid[i][j] = new Spot(i, j);
        }
    }
};

// SPOT CONSTRUCTOR
function Spot(i, j) {
    this.x = i;
    this.y = j;
    this.f = 0;
    this.g = 0;
    this.h = 0;
}

// GRID WITH NODE
const gridWithNode = () => {
    <div>
        {Grid.map((row, rowIndex) => {
            return (
                <div key={rowIndex} className='rowWrapper'>
                    {row.map((col, colIndex) => {
                        return (
                            <Node key={colIndex} />
                        )
                    })}
                </div>
            )
        })}
    </div>
}
console.log(Grid);
return (
    <div className="Wrapper">
        <h1>Pathfind Component</h1>
        {gridWithNode}
    </div>
  )
}

export default Pathfind;

1 Answer 1

1

Your function doesn't really return anything, it should return a valid jsx, so add a parenthesis around your function

// GRID WITH NODE
const gridWithNode = () => ( 
    <div>
        {Grid.map((row, rowIndex) => {
            return (
                <div key={rowIndex} className='rowWrapper'>
                    {row.map((col, colIndex) => {
                        return (
                            <Node key={colIndex} />
                        )
                    })}
                </div>
            )
        })}
    </div>
)

then invoke it inside your Wrapper div

{gridWithNode()}
Sign up to request clarification or add additional context in comments.

Comments

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.