Home > Net >  React multi level if conditional rendering not working
React multi level if conditional rendering not working

Time:12-22

I am using next.js and I have a page that renders a component.

export default function SamplePage() {
  return (
    <>
      {myData.map((countries) => {
        if (countries.title === "USA") {
          {
            countries.states.map((state) => {
              if (state.name === "NY") {
                console.log(state.name); // NY
                return <NYMap />;
              } elseif (state.name === "CA") {
                console.log(state.name); // Californima
                return <CaliforniaMap />;
              }
            });
          }
        }
      })}
    </>
  );
}

but I am not able to render <NYMap /> and <CaliforniaMap /> components. myData is passed correctly and using console log inside the if statements works just not displaying the component.

CodePudding user response:

Without an explicit return in the outer map what was being implicitly returned was undefined and there was nothing to render.

Add a return statement to the states mapping:

return countries.states.map((state) => {
  if (state.name === "NY") {
     console.log(state.name); // NY
     return <NYMap />;
  } elseif (state.name === "CA") {
     console.log(state.name); // Californima
     return <CaliforniaMap />;
  }
});
  • Related