Home > Back-end >  Map method is not working to render nested component in reactJs
Map method is not working to render nested component in reactJs

Time:12-15

I have this as top Component.

  const [allThreads, setAllThreads] = useState([{ post: "b" }]);
  
  return (
    <div className="App">
     
      <Main allThreads={allThreads} key={3} />
      
    </div>
  );
}
export default App;

This is my Main component.

import "../scss/App.scss";
import Thread from "./Thread";

function Main(props) {
  console.log("props received in Main"   JSON.stringify(props));
  return (
    <div className="main">
      <span>main</span>
      {props.allThreads.map((thread) => {
        console.log("appending posts in list");
        console.log(thread.post);
        <Thread post={thread.post} />;
      })}
    </div>
  );
}

export default Main;

and this is thread component.

import "../scss/App.scss";
function Thread(props) {
  console.log("reached thread method");
  return <div className="thread">{props.post}</div>;
}
export default Thread;

but iteration is never reaching Thread component. And this [{ post: "b" }] that i used as initial state is not getting printed on screen. What could be the issue? PFA output that is currently coming.enter image description here

CodePudding user response:

It is because you are not returning anything in your map. It is a common mistake. map always need to return something. Try with this :

import "../scss/App.scss";
import Thread from "./Thread";

function Main(props) {
  console.log("props received in Main"   JSON.stringify(props));
  return (
    <div className="main">
      <span>main</span>
      {props.allThreads.map((thread) => {
        console.log("appending posts in list");
        console.log(thread.post);
        return <Thread post={thread.post} />;
      })}
    </div>
  );
}

export default Main;
  • Related