Skip to content
This repository has been archived by the owner on Feb 9, 2024. It is now read-only.

London10 | Kristina Dubnyk | cyf-hotel-react | React #595

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ A hotel booking application in React. Homework for the [CodeYourFuture React mod

**Instructions:** Still in the `<Search />` component, add a `onSubmit` handler to the `<form>` tag. When the form is submitted (try clicking the search button), get the value of the state `searchInput` and pass it as a parameter to the `search` prop function that has been provided for you (the `search` prop is passed from the `<Bookings />` component).

**Note:** Also your submit handler should take an `event` parameter and add the line `event.preventDefault()` to prevent the browser to implicitely submit the form).
**Note:** Also your submit handler should take an `event` parameter and add the line `event.preventDefault()` to prevent the browser to implicitely submit the form.

**Test:** Look in the console, you should see the text that is typed in the search input field when submitting the form.

Expand Down Expand Up @@ -216,13 +216,13 @@ A hotel booking application in React. Homework for the [CodeYourFuture React mod

**Test:** Each column in the table should be clickable to sort results in ascending or descending order.

#### 26. Validate new booking
#### 26. Validate new booking

**Instructions:** Add validation to some fields from exercise 24: the first name and last name must not be empty, the email must contain exactly 1 `@` symbol, and at least one `.` symbol after the `@`; the room ID must be a number between 0 and 100. If the fields do not contain correct information when the 'Submit' button is pressed, display a red error message at the top of the page, but do not clear the text already in the field.

**Test:** An invalid input displays an error message after the 'Submit' button is pressed (e.g. an email like `react@com` is invalid). A valid input shows the correct values at the bottom of the page.

**Reflection:** Validating user input is an important part of any application. Without checking the input, you might see unexpected errors when working with the data later.
**Reflection:** Validating user input is an important part of any application. Without checking the input, you might see unexpected errors when working with the data later.

What do you think would happen if you were asked to remove a booking for room number '81', but the user had typed 'eightyOne' or 'EIGHTY ONE'?

Expand All @@ -234,27 +234,29 @@ What do you think would happen if you were asked to remove a booking for room nu

**Test:** The 'Submit' button is initially not clickable, and becomes clickable once every field has the correct input.

**Reflection:** You have used native form validations in HTML. How have you improved this feature with React?
**Reflection:** You have used native form validations in HTML. How have you improved this feature with React?

As a user of this booking system, would you prefer:

- To find out you made a mistake when you submit the whole form?
- To find out you made a mistake after each input?

#### 28. Date picker

**Instructions:** Add the [js-datepicker](https://www.npmjs.com/package/js-datepicker) package to your project using `npm install`, and import it at the top of the file. Add different IDs to your 'check in date' and 'check out date' `<input>` elements, then create two date pickers using `const checkInPicker = datepicker(YOUR_ID)` (where `YOUR_ID` is the ID you assigned to your check in/check out date elements).
**Instructions:** Add the [js-datepicker](https://www.npmjs.com/package/js-datepicker) package to your project using `npm install`, and import it at the top of the file. Add different IDs to your 'check in date' and 'check out date' `<input>` elements, then create two date pickers using `const checkInPicker = datepicker(YOUR_ID)` (where `YOUR_ID` is the ID you assigned to your check in/check out date elements).

**Hint:** Read the [js-datepicker usage guide](https://www.npmjs.com/package/js-datepicker#basic-usage)

**Test:** The date picker appears when you click on the 'check in date' and 'check out date' input elements.

**Reflection:** Using `js-datepicker` in this exercise allows you to practice installing and working with packages in JavaScript.
**Reflection:** Using `js-datepicker` in this exercise allows you to practice installing and working with packages in JavaScript.

Packages contain new functions and properties to work with that may not be available in native JavaScript/HTML. Using packages can often save time instead of writing your own functions, as you are importing code that someone else has written. However, this can have downsides; not all packages are high quality, and some may have bugs or may reduce accessibility by recreating native elements (`js-datepicker` recreates HTML's native [datepicker](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date) element).

Think about some of the code you have written in this lesson - are there any packages available that might have helped you to complete the exercises?

For example, exercise 26 and 27 used validation. Searching npmjs.com for '[validate](https://www.npmjs.com/search?q=validate)' shows multiple packages, such as '[validator](https://www.npmjs.com/package/validator)' and '[Validate](https://www.npmjs.com/package/Validate)'. Open both of these packages in your browser, and consider the following questions:

- Is it clear what this package does? Will it solve my specific problem better than writing my own code?
- Do I trust that the code in this package is safe to run on my machine? Do other people trust this package? (Hint: look at weekly downloads, last update, dependents, and visit the repository)
- Is this package accessible? Will it work on all browsers?
Expand Down
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"moment": "^2.29.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "^5.0.1"
Expand Down
5 changes: 5 additions & 0 deletions src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,8 @@ tr {
.card {
width: 18rem;
}

.selected-row {
/* border-radius: 3px solid rgb(97, 19, 243); */
background-color: #ead8fa;
}
10 changes: 8 additions & 2 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import React from "react";

import { Header } from "./Header";
import Bookings from "./Bookings";
import "./App.css";
import TouristInfoCards from "./TouristInfoCards";
import { Footer } from "./Footer";
import { Restaurant } from "./Restaurant";

const App = () => {
return (
<div className="App">
<header className="App-header">CYF Hotel</header>
<Header />
<TouristInfoCards />
<Bookings />
<Restaurant />
<Footer />
</div>
);
};
Expand Down
8 changes: 0 additions & 8 deletions src/App.test.js

This file was deleted.

34 changes: 28 additions & 6 deletions src/Bookings.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,40 @@
import React from "react";
import React, { useState, useEffect } from "react";
import Search from "./Search.js";
// import SearchResults from "./SearchResults.js";
// import FakeBookings from "./data/fakeBookings.json";
import SearchResults from "./SearchResults.js";

const Bookings = () => {
const search = searchVal => {
console.info("TO DO!", searchVal);
const [bookings, setBookings] = useState([]);

const search = (searchInput) => {
const convertedVal = searchInput.toLowerCase().trim();
const matched = bookings.filter(({ firstName, surname }) => {
return (
firstName.toLowerCase().includes(convertedVal) ||
surname.toLowerCase().includes(convertedVal)
);
});
setBookings(matched);
};

const fetchData = async () => {
try {
const response = await fetch("https://cyf-react.glitch.me");
const data = await response.json();
setBookings(data);
} catch (error) {
console.error("The ERROR is:", error);
}
};

useEffect(() => {
fetchData();
}, []);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice use of dependencies array, empty means the logic inside the useEffect will be executed once.


return (
<div className="App-content">
<div className="container">
<Search search={search} />
{/* <SearchResults results={FakeBookings} /> */}
<SearchResults data={bookings} />
</div>
</div>
);
Expand Down
54 changes: 54 additions & 0 deletions src/CustomerProfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import React, { useEffect, useState } from "react";

export default function CustomerProfile({ id }) {
// console.log("CustomerProfile props:", id);
const [clientData, setClientData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a minor suggestion here, if the variable is a boolean, naming it as isLoading, setIsLoading, isError ... is more intuitive.

This reference is of Java but I think this convention is widely adapted
https://geosoft.no/javastyle.html#Specific


const fetchClientData = async () => {
try {
setError(false);
setLoading(true);
const response = await fetch(
`https://cyf-react.glitch.me/customers/${id}`
);
// console.log("fetchClientData response", response);
if (!response.ok) {
throw Error();
}
const data = await response.json();
// console.log("fetchClientData data", data);
setClientData(data);
} catch (error) {
setError(true);
} finally {
setLoading(false);
}
};

useEffect(() => {
if (id) {
fetchClientData();
}
}, [id]);

return (
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of deciding the rendering within return, do you thiink moving the condition out and returning accordlingly is more readable?

if(loading) {
  retrun (
    <div>Loading...</div>
  )
}

if(error) {
  return (
  <div>Error</div>
  )
}

return (
  <>
    ...
  </>
 )

<>
{loading && <div>Loading...</div>}
{error && <div>Error</div>}
{clientData && !loading && !error && (
<>
<h1>Customer Profile</h1>
<h3>Customer ID: {clientData.id}</h3>
<h3>
Customer Name: {clientData.firstName} {clientData.surname}
</h3>
<h3>Customer Email: {clientData.email}</h3>
<h3>Customer Phone Number: {clientData.phoneNumber}</h3>
<h3>VIP : {clientData.vip ? "Yes" : "No"}</h3>
</>
)}
</>
);
}
17 changes: 17 additions & 0 deletions src/Footer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const location = [
"123 Fake Street, London, E1 4UD",
"[email protected]",
"0123 456789",
];

export function Footer() {
return (
<div className="footer">
<ul>
{location.map((element, index) => (
<li key={index}>{element}</li>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Happy to see you have the key attribute for each li

reference of key https://legacy.reactjs.org/docs/lists-and-keys.html#keys

))}
</ul>
</div>
);
}
3 changes: 3 additions & 0 deletions src/Header.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function Header() {
return <header className="App-header">CYF Hotel</header>;
}
41 changes: 32 additions & 9 deletions src/Restaurant.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,40 @@
import React from "react";
import React, { useState } from "react";

const Restaurant = () => {
const pizzas = 0;
export const Restaurant = () => {
return (
<div>
<h3>Restaurant Orders</h3>
<ul>
<li>
Pizzas: {pizzas} <button className="btn btn-primary">Add</button>
</li>
<div className="restuarant-container">
<h3 className="restaurant-header">Restaurant Orders</h3>
<ul className="list-of-food">
<Order food={"Pizza"} />
<Order food={"Salad"} />
<Order food={"Chocolate cake"} />
</ul>
</div>
);
};

function RestaurantButton(props) {
return (
<button onClick={props.setOrdersFunction} className="btn btn-primary">
Add
</button>
);
}

function Order(props) {
const [orders, setOrders] = useState(0);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if the variable is a number type rather than an array, it is better to name it order, orders implies it is an array.


function setOrdersFunction() {
setOrders(orders + 1);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI there is another way to update the state setOrders( (order) => order + 1). in this case the result is the same.

}

return (
<li className="food-item">
{props.food}: {orders}
<span> </span>
<RestaurantButton setOrdersFunction={setOrdersFunction} />
</li>
);
}

export default Restaurant;
26 changes: 22 additions & 4 deletions src/Search.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,41 @@
import React from "react";
import React, { useState } from "react";
import SearchButton from "./SearchButton";

const Search = (props) => {
const [searchInput, setSearchInput] = useState("");

function handleSearchInput(e) {
let searchValue = e.target.value.toLowerCase().trim();
setSearchInput(searchValue);
console.log(searchValue);
}

const handleSearchSubmit = (e) => {
e.preventDefault();
props.search(searchInput);
console.log("Search for:", searchInput);
};

const Search = () => {
return (
<div className="search">
<div className="page-header">
<h4 className="text-left">Search Bookings</h4>
</div>
<div className="row search-wrapper">
<div className="col">
<form className="form-group search-box">
<form className="form-group search-box" onSubmit={handleSearchSubmit}>
<label htmlFor="customerName">Customer name</label>
<div className="search-row">
<input
onChange={handleSearchInput}
value={searchInput}
type="text"
id="customerName"
className="form-control"
placeholder="Customer name"
label="Search"
/>
<button className="btn btn-primary">Search</button>
<SearchButton />
</div>
</form>
</div>
Expand Down
3 changes: 3 additions & 0 deletions src/SearchButton.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function SearchButton() {
return <button className="btn btn-primary">Search</button>;
}
Loading