ReactJS Exercises
Hello World App
Objective: Set up a basic React application and render a simple "Hello, World!" message.
Steps:
1. Use Create React App to set up a React project.
2. In [Link], return a simple message "Hello, World!" in JSX.
Code:
```javascript
function App() {
return <h1>Hello, World!</h1>;
}
```
Button Click Event
Objective: Create a button that updates a message when clicked.
Steps:
1. Create a button element.
2. Add an event listener for the onClick event.
3. Update the state to display a new message on button click.
Code:
```javascript
import React, { useState } from "react";
function App() {
const [message, setMessage] = useState("Click the button!");
const handleClick = () => {
setMessage("Hello, React!");
};
return (
<div>
<p>{message}</p>
<button onClick={handleClick}>Click Me!</button>
</div>
);
}
export default App;
```
Form Input and State Management
Objective: Capture user input from a form field and display it dynamically.
Steps:
1. Create an input field.
2. Use useState to manage the input field value.
3. Display the input value as the user types.
Code:
```javascript
import React, { useState } from "react";
function App() {
const [inputValue, setInputValue] = useState("");
const handleChange = (e) => {
setInputValue([Link]);
};
return (
<div>
<input type="text" value={inputValue} onChange={handleChange} />
<p>You typed: {inputValue}</p>
</div>
);
}
export default App;
```
Toggle Between Themes
Objective: Implement a toggle that changes the background color of the app between two
themes (light and dark).
Steps:
1. Set up two themes with different background colors.
2. Add a button to toggle between them.
3. Use useState to handle the current theme.
Code:
```javascript
import React, { useState } from "react";
function App() {
const [isDarkMode, setIsDarkMode] = useState(false);
const toggleTheme = () => {
setIsDarkMode(!isDarkMode);
};
return (
<div style={{ backgroundColor: isDarkMode ? "black" : "white", color: isDarkMode ?
"white" : "black" }}>
<button onClick={toggleTheme}>Toggle Theme</button>
<p>The current theme is {isDarkMode ? "Dark" : "Light"}</p>
</div>
);
}
export default App;
```
Conditional Rendering
Objective: Display different messages based on the state of a variable (logged in or not).
Steps:
1. Set up a state variable isLoggedIn.
2. Conditionally render content based on isLoggedIn.
Code:
```javascript
import React, { useState } from "react";
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{isLoggedIn ? (
<h1>Welcome Back!</h1>
):(
<button onClick={() => setIsLoggedIn(true)}>Log In</button>
)}
</div>
);
}
export default App;
```
Component Lifecycle (Class Component)
Objective: Implement lifecycle methods in a class component.
Steps:
1. Create a class component.
2. Use componentDidMount() to display a message when the component mounts.
3. Use componentWillUnmount() to clean up before unmounting.
Code:
```javascript
import React, { Component } from "react";
class App extends Component {
componentDidMount() {
[Link]("Component Mounted!");
}
componentWillUnmount() {
[Link]("Component Will Unmount!");
}
render() {
return <h1>Check the console for lifecycle events.</h1>;
}
}
export default App;
```
Functional Component with useEffect
Objective: Use useEffect to perform side effects like fetching data from an API.
Steps:
1. Use useEffect to fetch data when the component mounts.
2. Display the fetched data.
Code:
```javascript
import React, { useState, useEffect } from "react";
function App() {
const [data, setData] = useState(null);
useEffect(() => {
fetch("[Link]
.then((response) => [Link]())
.then((data) => setData(data));
}, []); // Empty dependency array ensures it runs only once (on mount)
return <div>{data ? <h1>{[Link]}</h1> : <p>Loading...</p>}</div>;
}
export default App;
```
Simple Counter with Hooks
Objective: Build a simple counter with increment and decrement buttons.
Steps:
1. Use useState to maintain a count.
2. Create buttons to increment and decrement the counter.
Code:
```javascript
import React, { useState } from "react";
function App() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
}
export default App;
```
Passing Props to Child Components
Objective: Pass data from a parent component to a child component using props.
Steps:
1. Create a parent and child component.
2. Pass data from the parent to the child through props.
Code:
```javascript
import React from "react";
function ChildComponent({ message }) {
return <h2>{message}</h2>;
}
function ParentComponent() {
return <ChildComponent message="Hello from Parent!" />;
}
export default ParentComponent;
```
Handling Forms with React
Objective: Create a form with controlled components (input fields controlled by React
state).
Steps:
1. Set up an input form with controlled components using useState.
2. Handle form submission to prevent default behavior and log input values.
Code:
```javascript
import React, { useState } from "react";
function App() {
const [inputValue, setInputValue] = useState("");
const handleSubmit = (e) => {
[Link]();
[Link](inputValue);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue([Link])}
/>
<button type="submit">Submit</button>
</form>
);
}
export default App;
```