Reputation: 326
Simple app. It just returns a <ul>
of <li>
elements.
Am I using useState()
correctly? I had to use Array.from()
before I could get the map function to work on taskList
. Before that, I was getting an error saying that taskList.map is not a function.
Here's App.js:
import React, { useState } from 'react';
import './App.css';
import ToDoList from './components/ToDoList';
import AddTask from './components/AddTask';
function App() {
const [ tasks, setTasks ] = useState(['Test task', 'other task', 'blah task'])
return (
<>
<ToDoList
taskList={tasks}
/>
</>
);
}
export default App;
Here's TodoList.js:
import React from 'react';
import Task from './Task';
import v4 from 'uuid';
export default function ToDoList(taskList) {
const listItems = Array.from(taskList).map((task) =>
<Task key={v4}
detail={task} />
);
return(
<ul>
{listItems}
</ul>
);
}
Here's Task.js:
import React from 'react';
export default function Task(key, detail) {
return ( // Number each item with keys... or an ol instead of ul
<li key={key}>
{detail}
</li>
)
}
Upvotes: 0
Views: 82
Reputation: 683
EDIT: here is a simple example to get you running https://codesandbox.io/s/jolly-meadow-m87s9?file=/src/App.js. It maps an array from the state to li elements and includes a handler to append the state.
Not sure which error you are still having? Regarding your Array.from/state question, use state this way instead:
[myState, setMyState ] = useState({list: ['item1', 'item2']})
Then you can map over the tasks by simply doing myState.list.map(item => ...)
Upvotes: 1