React - Level 5 - React Interactivity - Enhance Your Animal Gallery with State and Event Handling #255
akash-coded
started this conversation in
Tasks
Replies: 1 comment
-
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment


Uh oh!
There was an error while loading. Please reload this page.
-
Title: Enhance Your Animal Gallery with State and Event Handling!
Hello, React developers!
You've now learned about state in React, how to pass mutator functions through props, and how to handle click events. Let's put all that knowledge into practice by enhancing the Animal Gallery app (#253) you built earlier.
In this exercise, we'll add interactivity to your Animal Gallery by allowing users to "like" their favorite animals. You'll learn how to manage stateful data, pass mutator functions to child components, and handle events to update the UI.
🌟 Exercise Overview
Objective: Update your existing Animal Gallery app to allow users to like animals by clicking a button, and display the number of likes for each animal.
What You'll Learn:
useStatehook.map().🛠️ Let's Get Started!
Step 1: Set Up Your React App
If you completed the previous Animal Gallery exercise, you can use that code as your starting point. If not, you can create a new React app:
npx create-react-app animal-gallery cd animal-gallery npm startStep 2: Prepare Your Data with Initial State
We'll modify
App.jsto manage the animals array using React state.👉 Open
src/App.jsand update it as follows:Concepts Used:
useStateto manage theanimalsarray.Step 3: Update the Gallery Component
We'll update
Gallery.jsto receive and pass down thesetAnimalsfunction.👉 Open
src/Gallery.jsand update it:Concepts Used:
setAnimalsto child components.Step 4: Update the AnimalCard Component
We'll modify
AnimalCard.jsto display the number of likes and add a "Like" button.👉 Open
src/AnimalCard.jsand update it:Concepts Used:
onClickevent.setAnimalsto update the state immutably....).Step 5: Understanding the handleLike Function
Let's break down the
handleLikefunction:Explanation:
setAnimals: Updates the state ofanimals.prevAnimals: Represents the previous state.map(): Iterates over each animal in the array.a.name === animal.name: Finds the animal that was liked.{ ...a, likes: a.likes + 1 }: Returns a new object with the updated likes.Step 6: Add a "Dislike" Button (Optional)
Let's enhance the app by adding a "Dislike" button.
👉 Update
src/AnimalCard.jsto include a "Dislike" button:Concepts Used:
Step 7: Add Sorting Functionality
Let's sort the animals based on the number of likes.
👉 Update
src/Gallery.jsto sort animals:Concepts Used:
sort()to order animals.Step 8: Style Your App
Add some styles to make your app look better.
👉 Update
src/App.css:Step 9: Run Your App
Save all your files and make sure your development server is running (
npm start). Open your app in the browser and test the functionality:🔄 Recap and Concepts
1. State Management with
useStateuseStateHook: Allows you to add state to functional components.setAnimals) to change state.2. Passing Mutator Functions Through Props
Mutator Functions: Functions that change the state.
Props: Passing both data and functions to child components.
Example:
3. Handling Click Events
Event Handlers: Functions that respond to user interactions.
onClickEvent: Triggers when a user clicks an element.Example:
4. Updating State Immutably
Immutability: Avoid modifying the original state directly.
Creating New Objects/Arrays: Use the spread operator to create copies with updated values.
Example:
5. Using JavaScript Array Methods
map(): Transforming arrays by applying a function to each element.sort(): Sorting arrays based on a comparison function.Example:
🧩 Understanding the Code with Fill-in-the-Blanks
Let's revisit key parts of the code with blanks for you to fill in.
AnimalCard.js
📝 Hint: Return a new object with the updated number of likes.
🔑 Solution:
AnimalCard.js (Dislike Function)
📝 Hint: Decrease likes by 1, but only if likes are greater than zero.
🔑 Solution:
Gallery.js (Sorting Animals)
📝 Hint: Copy the
props.animalsarray before sorting.🔑 Solution:
🌟 Extra Challenges
Challenge 1: Implement a "Favorite" Feature
Allow users to mark animals as favorites and filter the gallery to show only favorites.
Steps:
Challenge 2: Add a Search Functionality
Allow users to search for animals by name.
Steps:
App.js.Gallerycomponent.Challenge 3: Animate Likes
Add a visual effect when the number of likes changes.
Hint: Use CSS transitions or React animations.
🧠 Test Your Understanding
Try to answer these questions:
Why do we use
prevAnimalsin thesetAnimalsfunction?Answer: To access the current state of
animalsbefore updating it.Why is it important to update state immutably in React?
Answer: Because mutating state directly can lead to unexpected behavior and bugs, as React relies on immutability to detect changes.
How does the
map()function help in updating state?Answer: It allows us to create a new array by transforming each element, which is essential for immutably updating state.
Understanding the Concepts
1. The
useStateHookSyntax:
Purpose: Adds state to functional components.
2. Passing Functions Through Props
Why: Allows child components to update state managed in a parent component.
Example:
3. Handling Events in React
Event Handler Functions: Functions that are called when an event occurs.
Binding Events:
4. Updating State Immutably
Avoid Direct Mutation: Do not modify state variables directly.
Create Copies: Use the spread operator or methods that return new arrays/objects.
5. JavaScript Array Methods
map(): Creates a new array by applying a function to each element.filter(): Creates a new array with elements that pass a test.sort(): Sorts elements in place based on a comparison function.🚀 Keep Experimenting!
Don't stop here! Here are some ideas to further enhance your app:
👩💻 Next Steps in React
Now that you're comfortable with state and event handling, consider exploring:
useEffectto handle side effects in your components.Keep up the great work, and happy coding!
Beta Was this translation helpful? Give feedback.
All reactions