Using Components to Structure React Web Applications

create-react-app

Functional versus Structural Components

The Component Hierarchy

An example of a Component Hierarchy
import React from “react”;
import Header from “./Header”;
import HomePage from “./HomePage”;
function App() {
return (
<div className=”app”>
<Header />
<HomePage />
</div>
);
}
export default App;
import React, { useEffect, useState } from “react”;
import NewItemForm from “./NewItemForm”;
import ItemList from “./ItemList”;
import Search from “./Search”;
function HomePage() {
const [items, setItems] = useState([]);
const [searchTerm, setSearchTerm] = useState(“”);
useEffect(() => {
fetch(“http://localhost:6001/items")
.then((r) => r.json())
.then((itemsArray) => {
setPlants(ItemsArray);
});
}, []);
function handleAddItem(newItem) {
const updatedPlantsArray = […items, newItem];
setItems(updatedItemsArray);
}
function handleUpdateItem(updatedItem) {
const updatedItemsArray = items.map((item) => {
if (item.id === updatedItem.id) {
return updatedItem;
} else {
return item;
}
});
setItems(updatedItemsArray);
}
const displayedItems = items.filter((item) => {
return item.name.toLowerCase().includes(searchTerm.toLowerCase());
});
return (
<main>
<NewItemForm onAddItem={handleAddItem} />
<Search
searchTerm={searchTerm}
onSearchChange={setSearchTerm} />
<ItemList
items={displayedItems}
onDeleteItem={handleDeleteItem}
onUpdateItem={handleUpdateItem} />
</main>
);
}
export default ItemPage;

Bringing it all together

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store