Home > Back-end >  why can't I render component from inside .map in reactjs?
why can't I render component from inside .map in reactjs?

Time:04-03

I want to display some components based on the data I got from an api using fetch. when I tried to debug it using console.log, it has a value but the component won't show.. what am I doing wrong here?

MasterRute.js

const MasterRute = () => {
  const [rute, setRute] = useState([]);

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

  const getRute = async (query='') => {
    const response = await fetch('http://localhost:8080/rute');
    const data = await response.json();
    setRute(data);
  }

  return (
    <div>
      {
        rute.map((item, index) => {
          if (index == 0) {
            console.log(index, item.nama_rute); // 0 Lorem
            (<div>{item.nama_rute}</div>)
          }
        })
      }
    </div>
  );

}

any help is appreciated

CodePudding user response:

Let's break down this return statement:

return (
    <div>
      {
        rute.map((item, index) => {
          if (index == 0) {
            console.log(index, item.nama_rute); // 0 Lorem
            (<div>{item.nama_rute}</div>)
          }
        })
      }
    </div>
  );

Loosely speaking, we can see that you're returning "a div element with some piece of JS inside it". Here's the "JS inside your div":

rute.map((item, index) => {
  if (index == 0) {
     console.log(index, item.nama_rute); // 0 Lorem
     (<div>{item.nama_rute}</div>)
  }
})

Now let's break this down. You have a .map() on an array that is supposed to accept a function that takes (item, index) and returns a value for that item and index.

But is this actually happening?

if (index == 0) {
  console.log(index, item.nama_rute);
  (<div>{item.nama_rute}</div>)
}

it's logging the value, but it isn't returning anything! the (<div>...</div>) might as well just be another console.log statement.

Try this:

if (index == 0) {
  console.log(index, item.nama_rute);
  return <div>{item.nama_rute}</div>;
} else {
  return <div>Not supported yet</div>
}

Hope this helps!

CodePudding user response:

I'm not sure you can use if statement inside jsx, try this :

return (
    <div>
      {rute.map((item, index) => (<>{index === 0 && <div>{item.nama_rute}</div></>}))}
    </div>
);
  • Related