I'm not sure exactly how you're planning on getting your data to your component but this example is how you could do it via the state. If you're having a specific component rendering a post or note, it would be better to do it via props. I would read the List and Keys docs for React.
Class Style
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class App extends Component {
constructor(props) {
super(props);
this.state = {
notes: ['hello', 'world', 'blah blah']
};
}
render() {
const noteItems = this.state.notes.map((note) =>
<li>{note}</li>
);
return (
<ul>{noteItems}</ul>
);
}
}
export default App;
ReactDOM.render(<App />, document.getElementById('root'));
Functional Style
It seems like the functional way of writing this is more preferred, this is how you would write that.
import React, { useState } from 'react';
function App() {
const [notes, setNotes] = useState(['hello', 'world', 'blah blah'])
return <ul>{notes.map((note) => <li>{note}</li>)}</ul>
}
export default App;
ReactDOM.render(<App />, document.getElementById('root'));
Answer from Jango on Stack OverflowLoop through an array of strings and render it as a Prop in a Component in React
React: Loop through array of strings
Loop through a string and add a class to each letter with react
Iterating over a `string` and rendering each character as a list item; what to use for `key`?
Videos
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);
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.