Intro react v8
Ini merupakan catatan belajar React.js. Kita mulai dari 0 untuk coba belajar dari awal.
Link
- Course: https://frontendmasters.com/courses/complete-react-v8/
- Course web link : https://react-v8.holt.courses/
- Example repo course : https://github.com/btholt/citr-v8-project
- Repo: react-v8-fem
Pure
React : API part of library
React DOM : buat render ke DOM
nama komponen harus CAPITALIZE contoh : const App
Cara Install
ada beberapa cara install react di dalam project kita.
Menggunakan CDN
<body>
<div id="root">not rendered</div>
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script>
// Your code is going to go here
</script>
</body>
Penjelasan API
const App = () => {
return React.createElement(
'div', // elemen yang mau dibuat
{}, // attribute untuk tag html. Misal Id, class, dll
React.createElement('h1', {}, 'Adopt Me!') // child nya (nested)
)
}
// ambil dengan div root untuk jadi tempat render
const container = document.getElementById("root");
// buat root di element yang sudah di-select sebelumnya
const root = ReactDOM.createRoot(container);
// render komponen App di div root
root.render(React.createElement(App));
Fungsi key di React
Basically React tries to keep track of components are swapped in order in a list and it does that by you giving it a unique key it can track. If it sees two things have swapped, it'll just move the components instead of re-rendering.
Handling User Input
Cara cara untuk handle input dari user. Ada dua yaitu Uncontrolled Form dan Controlled Form.
Uncontrolled Form
Kapan pakai nya? kalau kita hanya perlu tau value sebuah form ketika ingin submit. Ngga perlu pasang onChange. Contoh kode :
<form
onSubmit={(e) => {
e.preventDefault()
const formData = new FormData(e.target)
const obj = {
location: formData.get('location') ?? '',
animal: formData.get('animal') ?? '',
breed: formData.get('breed') ?? '',
}
setReqParams(obj)
}}
>
<label htmlFor="location">
Location
<input name="location" id="location" placeholder="Location" />
</label>
<label htmlFor="animal">
Animal
<select
onChange={(e) => {
setAnimal(e.target.value)
}}
onBlur={(e) => {
setAnimal(e.target.value)
}}
id="animal"
value={animal}
placeholder="Animal"
>
{ANIMALS.map((animal) => (
<option value={animal} key={animal}>
{animal}
</option>
))}
</select>
</label>
<label htmlFor="breed">
Breed
<select
id="breed"
name="breed"
disabled={breeds.length === 0}
placeholder="Breed"
>
{breeds.map((breed) => (
<option value={breed} key={breed}>
{breed}
</option>
))}
</select>
</label>
<button>Submit</button>
</form>
note: Animal masih pake onChange karena untuk breedList kita perlu tau ras / jenis / breed dari hewan apa yang ingin dimunculkan. Misal animalnya anjing, maka breedList akan render jenis breed yang ada di anjing. Misalnya, Husky dan Bulldog. Ngga mungkin dong breed anjing ada British Short hair / Maine Coon. Nah, kasus tersebut namanya controlled form.
Controlled Form
Secara umum, kita listen input dari user dengan onChange lalu simpan valuenya di state.
import React, { useState } from 'react';
const ControlledForm = () => {
// State to hold the form data
const [formData, setFormData] = useState({
username: '',
email: '',
});
// Event handler for form input changes
const handleChange = (event) => {
const { name, value } = event.target;
setFormData({
...formData,
[name]: value,
});
};
// Event handler for form submission
const handleSubmit = (event) => {
event.preventDefault();
// Do something with the form data, e.g., send it to a server
console.log('Form submitted with data:', formData);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="username">Username:</label>
<input
type="text"
id="username"
name="username"
value={formData.username}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default ControlledForm;
formDatais a state variable that holds the form data.handleChangeis an event handler that updates the state when the user types into the input fields.- The
valueattribute of each input is set to the corresponding property informData, making them controlled inputs. handleSubmitis an event handler that prevents the default form submission behavior and can be used to perform actions like sending the form data to a server.
Error Boundary
Memanfaatkan lifecycle ComponentDidCatch yang cuma ada di Class Component