Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why can't I render component from inside .map in reactjs?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading