I am very beginner in ReactJS and I want to do this small task. With ReactJs, Hook, Functions and not with Class.
A Simple Shopping list:
- a card with an unordered list
- next to each list item a button to delete
- an input field to add more items
- a button that contains the add function
That is what I so far did. but it does not work. when I on add-btn clicked, items does not add to list.
App Component:
import './App.css';
import ShowList from "./componenten/ShowList";
import AddList from "./componenten/AddList";
import React, {useState} from "react";
function App() {
const [items, setItems] = useState([
{itemName: 'Test Item 01'},
]);
return (
<div className="App">
<AddList setItema={[items,setItems]}/>
<ShowList items={items}/>
</div>
);
}
export default App;
AddList Component:
import React, {useState} from 'react';
import {Button, Input} from "antd";
export default function AddList ({items, setItems}){
const [inputValue, setInputValue] = useState('');
const handleAddButtonClick = () => {
const newItem ={
itemName: inputValue,
};
const newItems = [...items,newItem];
setItems(newItems);
setInputValue('');
}
return(
<>
<Input value={inputValue} onChange={(event) =>
setInputValue(event.target.value)}
className='addItemInput'
placeholder="Artikel hinzufügen" />
<Button
type="primary"
className='btn'
onClick={() => handleAddButtonClick()}
>Hinzufügen</Button>
</>
);
}
ShowList Component:
import React from 'react';
import {Button} from "antd";
export default function ShowList ({items}){
return(
<div className='itemList'>
{items.map((item) => (
<ul className='itemContainer'>
<li className='item-name'>
{item.itemName}
</li>
<div className='delete-btn'>
<Button type="primary" danger ghost>
Delete
</Button>
</div>
</ul>
))}
</div>
);
}
CodePudding user response:
You have a typo and a structural mistake here:
<AddList setItema={[items,setItems]}/>
The typo, clearly, is that setItema
is not the same as setItems
. But the structural mistake is that this is not how one would commonly pass multiple props to a component. Because this only passes one prop to the component, and that prop is an array. But the component is expecting multiple props:
export default function AddList ({items, setItems})
Pass the props separately:
<AddList items={items} setItems={setItems} />
CodePudding user response:
One thing is the way you are passing props to AddList
const [items, setItems] = useState([]);
the first variable is your state, and the second one a function that updates that state.
You can pass those variables as props to
<AddList items={items} setItems={setItems} />