Assignments Of Day 6: State and Events in React
Assignment 1: Simple Counter Application
Objective: Create a simple counter application using React. The counter should have two buttons: one for incrementing and one for decrementing the count.
Steps:
1. Create a new React component called Counter.
2. Use the useState hook to manage the state for the counter.
3. Create two functions:
o increment to increase the counter.
o decrement to decrease the counter.
4. Display the current count and the two buttons.
5. Implement onClick event handlers to trigger increment and decrement functions.
Solution:
javascript
Copy code
import React, { useState } from 'react';
function Counter() {
// Step 2: Declare state variable for count, initialized to 0
const [count, setCount] = useState(0);
// Step 3: Increment function
const increment = () => {
setCount(count + 1);
};
// Step 3: Decrement function
const decrement = () => {
setCount(count - 1);
};
return (
<div>
{/* Step 4: Display the current count */}
<h1>Count: {count}</h1>
{/* Step 5: Add buttons for increment and decrement */}
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;
Explanation:
1. State Variable Declaration:
The useState(0) hook initializes the count variable to 0. The first element in the array (count) holds the current state, and the second element (setCount) is used to update the state.
2. Increment and Decrement Functions:
o increment increases the count by 1.
o decrement decreases the count by 1. These functions call setCount with the new value.
3. Rendering the Count and Buttons:
o We display the count value inside an <h1> tag.
o Two buttons are created with onClick event handlers to call the increment and decrement functions when clicked.
Assignment 2: Toggle Button
Objective: Create a button that toggles between "ON" and "OFF" based on state. When the button is clicked, the text should toggle between these two values.
Steps:
1. Create a component called ToggleButton.
2. Use the useState hook to declare a boolean state variable for toggling the button's text.
3. Create a function toggle that toggles the value of the state (from true to false or vice versa).
4. Display the current text ("ON" or "OFF") and the button.
5. Use the onClick event handler to trigger the toggle function.
Solution:
javascript
Copy code
import React, { useState } from 'react';
function ToggleButton() {
// Step 2: Declare state variable "isOn" initialized to false (OFF)
const [isOn, setIsOn] = useState(false);
// Step 3: Function to toggle the state
const toggle = () => {
setIsOn(!isOn); // Flip the boolean value
};
return (
<div>
{/* Step 4: Display the current text ("ON" or "OFF") */}
<h1>{isOn ? 'ON' : 'OFF'}</h1>
{/* Step 5: Button to toggle */}
<button onClick={toggle}>Toggle</button>
</div>
);
}
export default ToggleButton;
Explanation:
1. State Variable Declaration:
isOn is a boolean state variable initialized to false (representing "OFF").
2. Toggle Function:
The toggle function flips the isOn value. If it's true, it becomes false, and vice versa. This is achieved using setIsOn(!isOn).
3. Rendering the Text and Button:
o The button's text is displayed based on the isOn state. We use a ternary operator: {isOn ? 'ON' : 'OFF'}.
o Clicking the button triggers the toggle function, changing the state.
Assignment 3: Change User's Name
Objective: Create a simple form with an input field to change a user's name. Display the updated name once it is changed.
Steps:
1. Create a component called ChangeName.
2. Use useState to manage the name state.
3. Create an onChange handler that updates the name state whenever the user types in the input field.
4. Display the current value of the name state below the input field.
Solution:
javascript
Copy code
import React, { useState } from 'react';
function ChangeName() {
// Step 2: Declare a state variable "name" initialized to an empty string
const [name, setName] = useState('');
// Step 3: Handler to update "name" state based on input field value
const handleChange = (event) => {
setName(event.target.value);
};
return (
<div>
<h1>Change User's Name</h1>
{/* Step 4: Input field to change name */}
<input
type="text"
placeholder="Enter your name"
value={name}
onChange={handleChange}
/>
{/* Display the updated name */}
<h2>Your name is: {name}</h2>
</div>
);
}
export default ChangeName;
Explanation:
1. State Variable Declaration:
We initialize name as an empty string with useState('').
2. Input Change Handler:
The handleChange function updates the name state when the user types in the input field. It uses event.target.value to get the current value of the input field.
3. Rendering the Input and Name:
o The input field's value is bound to the name state, and every time it changes, the onChange handler updates the name state.
o The updated name is displayed below the input field.
Assignment 4: Count Words in a Text Area
Objective: Create an application where a user can type text into a text area, and the app will display the number of words in the text.
Steps:
1. Create a component called WordCounter.
2. Use useState to store the text entered in the text area and the word count.
3. Create an onChange event handler for the text area to update the text state.
4. Use a function to calculate the number of words in the text state and display it.
Solution:
javascript
Copy code
import React, { useState } from 'react';
function WordCounter() {
// Step 2: Declare state variables "text" and "wordCount"
const [text, setText] = useState('');
const [wordCount, setWordCount] = useState(0);
// Step 3: Function to calculate and update word count
const handleChange = (event) => {
const newText = event.target.value;
setText(newText);
// Step 3: Update word count based on text
const words = newText.trim().split(/\s+/).filter(Boolean); // Split by spaces and filter out empty entries
setWordCount(words.length);
};
return (
<div>
<h1>Word Counter</h1>
{/* Step 4: Text area to input text */}
<textarea
rows="5"
cols="40"
value={text}
onChange={handleChange}
/>
<h2>Word Count: {wordCount}</h2>
</div>
);
}
export default WordCounter;
Explanation:
1. State Variables:
text holds the content typed into the text area, and wordCount stores the number of words.
2. Word Count Calculation:
In handleChange, we first update the text state with the new input. Then, we calculate the word count by splitting the text on spaces (split(/\s+/)) and filtering out any empty entries (filter(Boolean)), which ensures we don't count extra spaces.
3. Displaying the Word Count:
The word count is displayed dynamically as the user types in the text area.
Exercise for Practice:
1. To-Do List Application:
Create a to-do list application where users can add and remove tasks. Use useState to manage the list of tasks.
2. Temperature Converter:
Create a simple temperature converter that converts between Celsius and Fahrenheit. Use two input fields and update the conversion on every change.
These assignments should help students practice using React's useState hook to manage state and handle events effectively.
4o mini
You said:
more
ChatGPT said:
ChatGPT
Additional Assignments on State and Events in React
Assignment 5: Toggle Dark Mode
Objective: Create a simple application that toggles between dark mode and light mode. Use the useState hook to manage the theme state and change the background color accordingly.
Steps:
1. Create a component called DarkModeToggle.
2. Use useState to manage the isDarkMode state, which determines if dark mode is enabled.
3. Use conditional rendering to apply different styles for light and dark modes.
4. Add a button to toggle between light mode and dark mode.
Solution:
javascript
Copy code
import React, { useState } from 'react';
function DarkModeToggle() {
// Step 2: Declare state variable for dark mode (false by default)
const [isDarkMode, setIsDarkMode] = useState(false);
// Step 3: Function to toggle dark mode
const toggleDarkMode = () => {
setIsDarkMode(!isDarkMode); // Flip the boolean value
};
return (
<div style={{
backgroundColor: isDarkMode ? '#333' : '#fff',
color: isDarkMode ? '#fff' : '#000',
height: '100vh',
textAlign: 'center',
paddingTop: '50px'
}}>
{/* Step 4: Display the toggle button */}
<h1>{isDarkMode ? 'Dark Mode' : 'Light Mode'}</h1>
<button onClick={toggleDarkMode}>Toggle Mode</button>
</div>
);
}
export default DarkModeToggle;
Explanation:
1. State Variable:
The isDarkMode state variable tracks whether the dark mode is active. It is initialized as false, meaning light mode is active by default.
2. Toggling Dark Mode:
The toggleDarkMode function flips the value of isDarkMode when the button is clicked. This toggles between true (dark mode) and false (light mode).
3. Conditional Styling:
o The background color and text color are conditionally set based on the value of isDarkMode.
o If dark mode is enabled (isDarkMode === true), the background color is dark (#333), and text color is light (#fff), and vice versa.
4. Button to Toggle Mode:
A button is provided to toggle between light and dark modes when clicked.
Assignment 6: User Login Form with State
Objective: Create a simple user login form with state management for the username and password fields. Upon form submission, display the entered username and password.
Steps:
1. Create a LoginForm component.
2. Use useState to manage the state of the username and password fields.
3. Create an onSubmit function to handle the form submission.
4. Display the entered username and password after the form is submitted.
Solution:
javascript
Copy code
import React, { useState } from 'react';
function LoginForm() {
// Step 2: Declare state variables for username and password
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
// Step 3: Handle form submission
const handleSubmit = (event) => {
event.preventDefault(); // Prevent the default form submission behavior
alert(`Username: ${username} \nPassword: ${password}`);
};
return (
<div>
<h1>Login Form</h1>
<form onSubmit={handleSubmit}>
{/* Step 4: Username input field */}
<input
type="text"
placeholder="Enter username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
{/* Step 4: Password input field */}
<input
type="password"
placeholder="Enter password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
{/* Submit button */}
<button type="submit">Login</button>
</form>
</div>
);
}
export default LoginForm;
Explanation:
1. State Variables:
o username and password are initialized as empty strings using useState.
o These states are bound to the respective input fields, so the state is updated whenever the user types in the fields.
2. Handling Form Submission:
o The handleSubmit function prevents the default form submission behavior using event.preventDefault(). This allows us to display an alert with the entered username and password values when the form is submitted.
3. Input Fields and Event Handlers:
o The input fields' values are controlled by the state variables, and the onChange event handlers update the state accordingly.
4. Alert on Submit:
o Upon form submission, the entered username and password are displayed in an alert.
Assignment 7: Simple Todo App
Objective: Create a simple to-do list application where users can add tasks and delete them from the list. Use useState to manage the tasks.
Steps:
1. Create a TodoApp component.
2. Use useState to manage the list of tasks.
3. Create an input field for adding new tasks.
4. Implement an onClick event to add a new task to the list.
5. Implement an onClick event to delete tasks from the list.
Solution:
javascript
Copy code
import React, { useState } from 'react';
function TodoApp() {
// Step 2: Declare state variable for tasks (array)
const [tasks, setTasks] = useState([]);
const [newTask, setNewTask] = useState('');
// Step 3: Function to add a new task
const addTask = () => {
if (newTask) {
setTasks([...tasks, newTask]);
setNewTask(''); // Clear the input after adding task
}
};
// Step 5: Function to delete a task
const deleteTask = (taskToDelete) => {
setTasks(tasks.filter(task => task !== taskToDelete));
};
return (
<div>
<h1>Todo List</h1>
{/* Step 3: Input field for new task */}
<input
type="text"
value={newTask}
onChange={(e) => setNewTask(e.target.value)}
placeholder="Add a new task"
/>
<button onClick={addTask}>Add Task</button>
{/* Step 4: Display tasks */}
<ul>
{tasks.map((task, index) => (
<li key={index}>
{task} <button onClick={() => deleteTask(task)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default TodoApp;
Explanation:
1. State Variables:
o tasks is an array holding the list of tasks.
o newTask is a string that stores the value of the new task being added.
2. Adding a New Task:
o The addTask function adds the newTask to the tasks array. It also clears the input field by setting newTask to an empty string after adding.
3. Deleting a Task:
o The deleteTask function removes the task from the tasks array using the filter() method, which returns a new array excluding the task to be deleted.
4. Rendering Tasks:
o The tasks are displayed in an unordered list (<ul>), with each task as a list item (<li>). A delete button is rendered next to each task, which triggers the deleteTask function when clicked.
Assignment 8: Character Counter in Text Area
Objective: Create an application where the user can type into a text area, and the number of characters typed is displayed in real-time.
Steps:
1. Create a component called CharacterCounter.
2. Use useState to manage the text state.
3. Display the character count next to the text area.
4. Update the character count as the user types.
Solution:
javascript
Copy code
import React, { useState } from 'react';
function CharacterCounter() {
// Step 2: Declare state variable "text"
const [text, setText] = useState('');
// Step 3: Handle text change event
const handleTextChange = (event) => {
setText(event.target.value); // Update text state with new input value
};
return (
<div>
<h1>Character Counter</h1>
{/* Step 4: Text area */}
<textarea
value={text}
onChange={handleTextChange}
rows="5"
cols="50"
></textarea>
{/* Display the character count */}
<p>Character Count: {text.length}</p>
</div>
);
}
export default CharacterCounter;
Explanation:
1. State Variable:
The text state holds the value of the text entered into the text area.
2. Updating the State:
The handleTextChange function is called whenever the user types into the text area. It updates the text state with the current value of the text area.
3. Displaying Character Count:
The length of the text string is displayed dynamically in the paragraph below the text area.
