-1

The issue is that the variable is having the value when I console.log but it is not rendering in the page. The loop print only the first data and other data is not printed.

const langData = [
  {
    name: "Front-End",
    children: [
      {
        name: "HTML"
      },
      {
        name: "CSS"
      },
      {
        name: "JS"
      }
    ]
  }
];
const renderName = ({ name, children }) => {
  console.log(name);
  return (
    <>
      <p>{name}</p>
      {children && children.forEach(newData => renderName(newData))}
    </>
  );
};

const App = () => {
  return <div className="App">{renderName(langData[0])}</div>;
};

Eg: Front-End will be on the page. Other data such as HTML, CSS, JS not showing in the page. But these variables are in the console.log. Not sure I miss to return any value.

Codesandbox link: https://codesandbox.io/s/reverent-ardinghelli-6snby?fontsize=14

Jijin P
  • 258
  • 1
  • 9
  • 21

3 Answers3

4

Using map you can get go over the array. The reason why map works and forEach does not is because map returns a new array while forEach does not return anything(returns undefined). You also need to add keys to get rid of the warning. I've used the index of the array as the key here:

const renderName = ({ name, children }, key) => {
  console.log(name);
  return (
    <>
      <div key={key}>
      <p>{name}</p>
      {children && children.map((newData,index) => renderName(newData, index))}
      </div>
    </>
  );
};
Winston Jude
  • 569
  • 2
  • 11
1

with render an array, you should use map, because .forEach always return undefined:

const renderName = ({ name, children, index }) => {
  console.log(name);
  return (
    <div key={index}>
      <p>{name}</p>
      {children && children.map((item, index)=> {
        const { name } = item;
        return renderName({name, index})
      })}
      {/* {children && children.forEach(newData => renderName(newData))} */}
    </div>
  );
};
aldenn
  • 2,060
  • 2
  • 11
  • 30
0

Try this you will directly get your result.

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";
const langData = [
  {
    name: "Front-End",
    children: [
      {
        name: "HTML"
      },
      {
        name: "CSS"
      },
      {
        name: "JS"
      }
    ]
  }
];
const renderName = (name,data) => (
  //console.log(name);
  <>
    <p>{name}</p>
    {data && data.map(child => (
      <p>{child.name}</p>
    ))}
  </>
);

const App = () => {
  return <div className="App">{renderName(langData[0].name,langData[0].children)}</div>;
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Prakash Karena
  • 2,525
  • 1
  • 7
  • 16