0

I'm trying to iterate through an array of objects, displaying the results inside divs but something is not working as intended. When I console log it seems to retrieve the data and show it.

const example =
      {
          "example": [
             {
               "test": "test",
               "img": "img.png",
               "song": "song title"
             },
             {
               "test": "test2",
               "img": "img.png2",
               "song": "song title2"
             }
           ]
         }

     const renderData= () => {
          example.example.forEach(function (arrayItem) {
            const test= arrayItem.test
            const img= arrayItem.img
            const song= arrayItem.song
            
            return (
              <div className="test">
              <div className="test">
                <div className="test">
                  <img
                    src={img}
                    alt="sunil"
                  />
                </div>
                <div className="test">
                    {test}
                    <span className="test">
                    </span>
                  <p>{song}</p>
                </div>
              </div>
            </div>
            );
          });
        };


return (
      <div
     
          {renderData()}
    
      </div>
    );
}

nothing really shows up, but when i do:

     example.example.forEach(function (arrayItem) {
      var x = arrayItem.test+ arrayItem.img+ arrayItem.song;
      console.log(x);
  });

it works and consoles the right info.

Can anyone spot the mistake or help out?

Please ignore the naming convention.

1 Answer 1

3

You need return array of JSX.Element from renderData. In your case you return undefined. Return a new array of JSX.Element with map instead forEach, which returns nothing.

const renderData = () => {
    return example.example.map((arrayItem, i) => {
        const test = arrayItem.test;
        const img = arrayItem.img;
        const song = arrayItem.song;

        return (
            <div key={i} className="test">
                <div className="test">
                    <div className="test">
                        <img src={img} alt="sunil" />
                    </div>
                    <div className="test">
                        {test}
                        <span className="test"></span>
                        <p>{song}</p>
                    </div>
                </div>
            </div>
        );
    });
};
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.