index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
ReactDOM.render(<App />, document.getElementById("root"));
//CHALLENGE: I have extracted the Input Area, including the <input> and
//<button> elements into a seperate Component called InputArea.
//Your job is to make the app work as it did before but this time with the
//InputArea as a seperate Component.
// DO NOT: Modify the ToDoItem.jsx
// DO NOT: Move the input/button elements back into the App.jsx
//Hint 1: You will need to think about how to manage the state of the input element
//in InputArea.jsx.
//Hint 2: You will need to think about how to pass the input value back into
//the addItem() function in App.jsx.
App.jsx
import React, { useState } from "react";
import ToDoItem from "./ToDoItem";
import InputArea from "./InputArea";
function App() {
const [items, setItems] = useState([]);
function addItem(inputText) {
setItems(prevItems => {
return [...prevItems, inputText];
});
}
function deleteItem(id) {
setItems(prevItems => {
return prevItems.filter((item, index) => {
return index !== id;
});
});
}
return (
<div className="container">
<div className="heading">
<h1>To-Do List</h1>
</div>
<InputArea onAdd={addItem} />
<div>
<ul>
{items.map((todoItem, index) => (
<ToDoItem
key={index}
id={index}
text={todoItem}
onChecked={deleteItem}
/>
))}
</ul>
</div>
</div>
);
}
export default App;
InputArea.jsx
import React, { useState } from "react";
function InputArea(props) {
const [inputText, setInputText] = useState("");
function handleChange(event) {
const newValue = event.target.value;
setInputText(newValue);
}
return (
<div className="form">
<input onChange={handleChange} type="text" value={inputText} />
<button
onClick={() => {
props.onAdd(inputText);
setInputText("");
}}
>
<span>Add</span>
</button>
</div>
);
}
export default InputArea;
ToDoItem.jsx
import React from "react";
function ToDoItem(props) {
return (
<div
onClick={() => {
props.onChecked(props.id);
}}
>
<li>{props.text}</li>
</div>
);
}
export default ToDoItem;
'프로그래밍 > Web' 카테고리의 다른 글
Web Programming Cheatsheet (0) | 2024.08.22 |
---|---|
ES6 Spread Operator - How to Simplify Your Code (0) | 2024.05.13 |
Changing Complex State - What to Do When You have Functions that Do the Same Thing (0) | 2024.05.10 |
Difference between Class and Functional Component (0) | 2024.05.09 |
Event Handling in React - How to Handle React Forms (0) | 2024.05.08 |