React Forms
Forms in React require the use of State to track input data. This is achieved by setting the field value to a state variable, and calling the set variable state function in the onChange event. Responding to the form submission is handled by a function in the component called when the onSubmit event occurs. preventDefault() is called to stop the browser attempting to handle the form submission.
import { useState } from "react";
function MyForm () {
const [name, setName] = useState("");
function handleSubmit() {
e.preventDefault();
// TODO: do something with the form data.
}
return (
<form onSubmit={handleSubmit}>
<input type="text" value={name} onChange={(e) => {setName(e.target.value)} />
<button type="submit">Submit</button>
</form>
);
}
export default MyComponent;
List Rendering
React can render a collection of data into a list of react components. To do so, two components are used: ComponentList, ComponentItem.
Using the array.map(func) function, a ComponentItem can be created for each data item in a collection.
Component Item:
function ScheduleItem({ booking }) {
return (
<div>
{booking.name}: {booking.date} @ {booking.time}
</div>
);
}
export default ScheduleItem;
Component List
import ScheduleItem from "./ScheduleItem";
function ScheduleList({ bookings }) {
if (bookings.length === 0) {
return (
<h3>Schedule is clear.</h3>
);
}
return (
<>
<h3>Schedule</h3>
{bookings.map((b, index) => (
<ScheduleItem key={index} booking={b} />
))}
>
);
}
export default ScheduleList;
State Lifting
State data can be transferred between components by "lifting" the data out of the component to a common parent (such as App.jsx).
import { useState } from "react";
function App() {
// Create array in state
const [schedule, setSchedule] = useState([]);
// Function for adding to the array
function addBooking(booking) {
setSchedule(oldSchedule => [...oldSchedule, booking]);
}
return (
<>
<Form onAdd={addBooking} /> // pass the function to the form
<ScheduleList bookings={schedule} /> // pass the array to the list component
</>
);
}
export default App;