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

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

/n will show next message in new line


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 rather than array.forEach().


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.


Here's an example of what could work for you: (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 () => {
  }, [messages, messageIndex]);

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

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

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

Related Query

More Query from same tag