I am new to StackOverflow and asking questions and such, so bear with me, and let me know if I am missing any useful information. I am working on a productivity web app for my fiance for her job, and this is a notes section of the app. I currently have the program fetching from an API I made, storing the code in a state variable, and then I have a JSX expression in the component to map the list of notes retrieved from the server. Here is kind of how it is setup:
const Notes = () => {
const [notesList, setNotesList] = useState([]);
useEffect(() => {
//loadNotes runs a fetch GET request to the server, here's what is being returned in the :
//{notes: [{ title: "Title", content: "This is the content of the note.", lastModified: "" }, { title: "Title 2", content: "This is the content of the second note.", lastModified: "" }]}
loadNotes().then(data => setNotesList(data.notes))
}, [])
return
<div className="notes-list">{notesList.map(item => return <NoteTab title={item.title} content={item.content} lastModified={item.lastModified} />)</div>
}
Every time I run the program, I receive this error:
Objects are not valid as a React child (found: object with keys {title, content, lastModified}). If you meant to render a collection of children, use an array instead.
I have tried a bunch of different things, like spread operators on the notesList in the JSX, mapping in the useEffect function, taking off the return from the mapping, and a bunch more. Any suggestions would be great as I’ve been stuck on this for two days. Thanks!
2
Answers
Here’s a problem, that
return
keyword should not be there.=>
implies returnitem => return <NoteTab…
Fix it to:
item => <NoteTab…
There are several problems going on with the code that you are writing. Eric Fortis above pointed out one of them, which was with an arrow function, you don’t need a return statement when you return on the same line and there are no curly brackets.
Further Breakdown:
Other than that, there are some formatting errors in your code above. However, I’ll assume that those are all typos, and that you typed these in separately because otherwise, your code would not work at all (if directly copy/pasted into a react app).
Here is a working example of your code that solves the problem you mentioned about the object child.
Hopefully that helps you a bit more.