“Mastering ReactJS Components: 10 Engaging Coding Exercises to Level Up Your Skills!”

“Mastering ReactJS Components: 10 Engaging Coding Exercises to Level Up Your Skills!”

Here are 10 practice coding exercises based on the concepts of ReactJS components:

Exercise 1: Render Props – Tabs Component

Create a Tabs component using Render Props. The component should display a list of tabs, and when a tab is clicked, it should render the corresponding content.

```jsx
import React, { useState } from 'react';
const Tabs = ({ children }) => {
const [activeTab, setActiveTab] = useState(0);
return (
<div>
<div>
{children.map((tab, index) => (
<button key={index} onClick={() => setActiveTab(index)}>
{tab.props.label}
</button>
))}
</div>
<div>{children[activeTab]}</div>
</div>
);
};

// Usage
const App = () => {
return (
<Tabs>
<div label="Tab 1">Content of Tab 1</div>
<div label="Tab 2">Content of Tab 2</div>
<div label="Tab 3">Content of Tab 3</div>
</Tabs>
);
};
```

Exercise 2: Context API – Dark Mode

Implement a DarkModeToggle component using Context API. The component should toggle the dark mode when the button is clicked.

```jsx
import React, { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
const DarkModeToggle = () => {
const theme = useContext(ThemeContext);
const toggleTheme = () => {
theme === 'light' ? setTheme('dark') : setTheme('light');
};
return (
<button onClick={toggleTheme}>
{theme === 'light' ? 'Switch to Dark Mode' : 'Switch to Light Mode'}
</button>
);
};
const App = () => {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<div>
<h1>App Content</h1>
<DarkModeToggle />
</div>
</ThemeContext.Provider>
);
};
```

Exercise 3: Error Boundaries – Error Handling

Create an ErrorBoundary component that catches errors in its child components. Display an error message when an error occurs.

```jsx
import React, { Component } from 'react';
class ErrorBoundary extends Component {
state = {
hasError: false,
};
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong. Please try again.</h1>;
}
return this.props.children;
}
}
const ComponentThatMightError = () => {
const throwError = () => {
throw new Error('Error occurred!');
};
return <button onClick={throwError}>Throw Error</button>;
};

// Usage
const App = () => {
return (
<ErrorBoundary>
<ComponentThatMightError />
</ErrorBoundary>
);
};
“`

Exercise 4: React Portals – Modal

Implement a Modal component using React Portals. The Modal should render outside of its parent component and display a message.

```jsx
import React from 'react';
import ReactDOM from 'react-dom';
const Modal = ({ children }) => {
return ReactDOM.createPortal(
<div className="modal">{children}</div>,
document.getElementById('modal-root')
);
};

// Usage
const App = () => {
return (
<div>
<h1>App Content</h1>
<Modal>This is a modal content.</Modal>
</div>
);
};
```

Exercise 5: Memoization – Expensive Computation

Create an ExpensiveComponent that performs an expensive computation using React Memoization. The component should display the result when a button is clicked.

```jsx
import React, { useState, useMemo } from 'react';
const ExpensiveComponent = ({ value }) => {
const expensiveResult = useMemo(() => {
// Expensive computation based on value
// For demonstration, a simple multiplication is used here
return value   2;
}, [value]);
return (
<div>
<p>Input Value: {value}</p>
<p>Expensive Result: {expensiveResult}</p>
</div>
);
};

// Usage
const App = () => {
const [inputValue, setInputValue] = useState(0);
return (
<div>
<input
type="number"
value={inputValue}
onChange={(e) => setInputValue(Number(e.target.value))}
/>
<ExpensiveComponent value={inputValue} />
</div>
);
};
```

Exercise 6: Render Props – Tooltip Component

Create a Tooltip component using Render Props. The component should display a tooltip when hovering over its child element.

```jsx
import React from 'react';
const Tooltip = ({ content, children }) => {
return (
<div className="tooltip">
{children}
<span className="tooltiptext">{content}</span>
</div>
);
};

// Usage
const App = () => {
return (
<Tooltip content="Hover over me!">
<button>Hover</button>
</Tooltip>
);
};
```

Exercise 7: Context API – User Authentication

Implement a UserProvider component using Context API to manage user authentication state. The component should provide user information to its child components.

```jsx
import React, { createContext, useContext, useState } from 'react';
const UserContext = createContext();
const UserProvider = ({ children }) => {
const [user, setUser] = useState(null);
const login = (userData) => {
setUser(userData);
};
const logout = () => {
setUser(null);
};
return (
<UserContext.Provider value={{ user, login, logout }}>
{children}
</UserContext.Provider>
);
};
const UserProfile = () => {
const { user, logout } = useContext(UserContext);
return (
<div>
{user ? (
<div>
<p>Welcome, {user.username}!</p>
<button onClick={logout}>Logout</button>
</div>
) : (
<p>Please log in to continue.</p>
)}
</div>
);
};

// Usage
const App = () => {
return (
<UserProvider>
<UserProfile />
</UserProvider>
);
};
```

Exercise 8: Error Boundaries – Error Handling with Retry

Enhance the ErrorBoundary component from Exercise 3 to allow users to retry the operation after an error occurs.

```jsx
// Code for enhancing ErrorBoundary component
```

Exercise 9: React Portals – Dialog Box

Implement a DialogBox component using React Portals. The DialogBox should appear on top of the page content and display a message.

```jsx
// Code for implementing DialogBox with React Portals
```

Exercise 10: Memoization – Fibonacci Sequence

Create a Fibonacci component that calculates and displays the nth Fibonacci number using React Memoization.
```jsx
import React, { useState, useMemo } from 'react';
const Fibonacci = ({ n }) => {
const calculateFibonacci = (n) => {
if (n <= 1) {
return n;
}
return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);
};
const fibonacciNumber = useMemo(() => calculateFibonacci(n), [n]);
return (
<div>
<p>The {n}th Fibonacci number is: {fibonacciNumber}</p>
</div>
);
};

// Usage
const App = () => {
const [n, setN] = useState(10);
return (
<div>
<input
type="number"
value={n}
onChange={(e) => setN(Number(e.target.value))}
/>
<Fibonacci n={n} />
</div>
);
};
```

Explanation:

  1. The `Fibonacci` component takes a prop `n`, which represents the index of the Fibonacci number to be calculated.
  2. The `calculateFibonacci` function is a recursive function to compute the nth Fibonacci number.
  3. We use `useMemo` to memoize the result of the Fibonacci calculation for a given value of `n`. This ensures that the computation is only performed when `n` changes, preventing unnecessary recalculations.

The `App` component is used to demonstrate the `Fibonacci` component. The user can input a value for `n`, and the `Fibonacci` component will efficiently compute and display the nth Fibonacci number.

Try changing the value of `n` in the input field, and you’ll notice that the Fibonacci number is calculated instantly with memoization, even for large values of `n`. This optimization significantly improves performance and enhances the user experience.

1 thought on ““Mastering ReactJS Components: 10 Engaging Coding Exercises to Level Up Your Skills!””

Leave a comment