Photo by Andrew Neel on Unsplash
Day 20 of 100days of code
Hello and welcome to day 20 of my challenge!πͺ
Add friend to the list
- Created two state variables:
friendsName
andimgUrl
.friendsName
is initialized with an empty string (""
), andimgUrl
is initialized with a default URL (" "
). I've also implemented two input elements, each linked to their respective state variables (friendsName
andimgUrl
) using thevalue
attribute. Furthermore, theonChange
event handler is employed to dynamically update the corresponding state variables as the user interacts with the input fields, ensuring real-time synchronization between the input content and the React component's state.πππ
Below, I've initialized the imgUrl
state variable with the default URL "https://i.pravatar.cc/48"
. At line 94 I implemented a handleSubmit
function for handling form submissions.ππ
Form Submission Handling:
The handleSubmit
function takes an event object (e
) as a parameter and is triggered when the form is submitted. Utilizing e.preventDefault();
, it prevents the default form submission behavior to enable custom logic and avoid page reload.
Form Input Validation:
The function checks if either friendsName
or imgUrl
is empty. If either is empty, the function returns early, preventing the execution of subsequent code
Generating a Unique ID:
A unique identifier is generated using the crypto.randomUUID()
function, providing a unique ID for the new friend object
Creating a New Friend Object:
A new friend object is created with properties:
name: extracted from the
friendsName
state.balance: initialized to 0.
image: constructed by appending the generated ID to the
imgUrl
to ensure a unique image URL.id: the unique identifier generated earlier. Currently, this information is logged to the console.
Resetting Input Fields:
After successfully adding the friend, the imgUrl
state is reset to a default avatar URL, and the friendsName
state is set to an empty string, effectively clearing the input fields in the form.
The component returns a JSX structure representing a form with the className of "form-add-friend." The onSubmit
event is set to trigger the handleSubmit
function when the form is submitted.πππ
The handleAddFriend
function is tasked with adding a new friend to the friendList
state. It utilizes the setFriendList
function, employing the functional form of setState
. This involves spreading the current state ([...friendList]
) and appending the new friend (friend
) to the end of the array. This approach ensures immutability by creating a fresh array containing both the existing friends and the new friend.ππ
This handleAddFriend
function handed down as a prop onAddFriend
to child components, FormAddFriend
component, where users create new friends. It gets triggered upon submitting the form to add a friend.
The highlighted line executes the onAddFriend
function, passing the newFriend
object as an argumentππ
A minor modification is needed on line 105ππ