score:-1

You can append message in a variable and return that variable in renderMessage function

const renderMessages = (msgs) => {
    let msgList = ""
    console.log(msgs);
    return msgs.forEach((msg, i) => {
        msgList = msgList + "/n" + msg
        setTimeout(() => {
            return <Message>{msgList}</Message>;
        }, 500);
    });
};

/n will show next message in new line

score:-1

What does you program not do as expected? Do the messages not show?

If you want to render some element while iterating through an aray, i would advise to use array.map() rather than array.forEach().

score:0

A functional component has to return the jsx to render. What you are trying to do does not work. In case of an array of messages you are returning msgs.forEach(...) but Array.prototype.forEach does not return an array but undefined.

You will need to use state to queue up the messages one by one and render the contents of that state instead.

score:4

Here's an example of what could work for you: https://codesandbox.io/s/loop-through-array-with-react-d5tlc (I would suggest reviewing it for edge cases but the core functionality should be close to what you're looking for).

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const messages = ["fetching from sources...", "loading account..."];

const Loader = props => {
  const { messages } = props;
  // Default to the first message passed
  const [messageIndex, setMessageIndex] = React.useState(0);

  React.useEffect(() => {
    // Move on to the next message every `n` milliseconds
    let timeout;
    if (messageIndex < messages.length - 1) {
      timeout = setTimeout(() => setMessageIndex(messageIndex + 1), 1000);
    }

    return () => {
      clearTimeout(timeout);
    };
  }, [messages, messageIndex]);

  return <div>{messages[messageIndex]}</div>;
};

function App() {
  return (
    <div className="App">
      <Loader messages={messages} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Related Query

More Query from same tag