React Coding Practice
Q. Create a multilevel dropdown menu in React?
Input: [
{
label: "Menu 1",
},
{
label: "Menu 2",
submenu: [{ label: "Sub Menu 1" }, { label: "Sub Menu 2" }],
},
{
label: "Menu 3",
submenu: [
{ label: "Sub Menu 1" },
{ label: "Sub Menu 2" },
{ label: "Sub Menu 3" },
{ label: "Sub Menu 4" },
],
},
{
label: "Menu 4",
submenu: [{ label: "Sub Menu 1" }, { label: "Sub Menu 2" }],
},
];
Answer
```js import React, { useState } from "react"; const menuData = [ { label: "Menu 1" }, { label: "Menu 2", submenu: [{ label: "Sub Menu 1" }, { label: "Sub Menu 2" }], }, { label: "Menu 3", submenu: [ { label: "Sub Menu 1" }, { label: "Sub Menu 2", submenu: [ { label: "Nested Sub Menu 1" }, { label: "Nested Sub Menu 2" }, ], }, { label: "Sub Menu 3" }, ], }, { label: "Menu 4", submenu: [{ label: "Sub Menu 1" }, { label: "Sub Menu 2" }], }, ]; function MenuItem({ item }) { const [open, setOpen] = useState(false); const hasSubmenu = Array.isArray(item.submenu) && item.submenu.length > 0; return ( <li style=> <button onClick={() => hasSubmenu && setOpen((prev) => !prev)} style= > {item.label} {hasSubmenu ? (open ? "-" : "+") : ""} </button> {hasSubmenu && open && ( <ul style= > {item.submenu.map((subItem, index) => ( <MenuItem key={`${subItem.label}-${index}`} item={subItem} /> ))} </ul> )} </li> ); } export default function App() { return ( <div style=>Multi-Level Dropdown Menu
<ul style=> {menuData.map((item, index) => ( <MenuItem key={`${item.label}-${index}`} item={item} /> ))} </ul> </div> ); } ```Q. Create a functional component that displays data from https://reqres.in/api/users?
Answer
```js import { useEffect, useState } from "react"; import axios from "axios"; export default function App() { const [users, setUsers] = useState<{ id: number; name: string; email: string }[]>([]); useEffect(() => { axios.get("https://jsonplaceholder.typicode.com/users").then((response) => { setUsers(response.data); }); }, []); return (-
{users.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
Q. Write a program to display searched keyword in React?
Answer
```js import { useState } from "react"; function App() { const [search, setSearch] = useState(""); return (Update Data from an input
Searched Keyword: {search}
<input
className="input"
type="text"
value={search}
placeholder="Search Here"
onChange={(e) => setSearch(e.target.value)}
/>
Q. Create a functional component to show an alert message based on user input?
Answer
```js import { useEffect, useState } from "react"; function App() { const [phrase, setPhrase] = useState(""); useEffect(() => { if (phrase === "Hello React") { alert("You may pass!"); } }, [phrase]); return (What is the secret phrase?
<input type="text" value={phrase} onChange={(e) => setPhrase(e.target.value)} placeholder="Enter a secret" />Hint: It is Hello React
Q. Create a functional component in react to add two numbers?
Answer
```js import { useState } from "react"; export default function App() { const [number1, setNumber1] = useState(0); const [number2, setNumber2] = useState(0); return (Adding Two Numbers
<input
type="number"
value={number1}
onChange={(e) => setNumber1(+e.target.value)}
/>
<input
type="number"
value={number2}
onChange={(e) => setNumber2(+e.target.value)}
/>
Total: {number1 + number2}
Q. Create a simple counter in react?
Answer
```js import { useCallback, useState } from "react"; const App = () => { const [counter, setCounter] = useState(0); const increment = useCallback(() => setCounter((c) => c + 1), []); const decrement = useCallback(() => setCounter((c) => c - 1), []); return (Counter: {counter}
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
Q. Write a program to pass values to child using context in React?
Answer
```js // Counter.js const { useState, useContext } = React; const CountContext = React.createContext(); const Counter = () => { const { count, increase, decrease } = useContext(CountContext); return (<button onClick={decrease}>Decrement</button> {count} <button onClick={increase}>Increment</button>
); }; ``` ```js // App.js const App = () => { const [count, setCount] = useState(0); const increase = () => { setCount(count + 1); }; const decrease = () => { setCount(count - 1); }; return (Q. Create a simple ToDo list app using React?
Answer
```js import { useCallback, useState } from "react"; interface Todo { id: number; text: string; completed: boolean; } export default function App() { const [todos, setTodos] = useState<Todo[]>([]); const [input, setInput] = useState(""); const addTodo = useCallback(() => { const trimmed = input.trim(); if (!trimmed) return; setTodos((prev) => [ ...prev, { id: Date.now(), text: trimmed, completed: false }, ]); setInput(""); }, [input]); const toggleTodo = useCallback((id: number) => { setTodos((prev) => prev.map((todo) => todo.id === id ? { ...todo, completed: !todo.completed } : todo, ), ); }, []); const deleteTodo = useCallback((id: number) => { setTodos((prev) => prev.filter((todo) => todo.id !== id)); }, []); const handleKeyDown = useCallback( (e: React.KeyboardEventToDo List
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Add a new task…"
/>
<button onClick={addTodo}>Add</button>
{todos.length === 0 ? (
No tasks yet. Add one above!
) : (-
{todos.map((todo) => (
<li key={todo.id}>
<input
type="checkbox"
checked={todo.completed}
onChange={() => toggleTodo(todo.id)}
/>
<span
style=
>
{todo.text}
</span>
<button
onClick={() => deleteTodo(todo.id)}
aria-label="Delete task"
>
X
</button>
</li>
))}
{todos.filter((t) => t.completed).length} / {todos.length} completed
)}Answer
```js import { useMemo, useState } from "react"; export default function App() { const [searchItem, setSearchItem] = useState(""); const searchResults = useMemo( () => people.filter((person) => person.toLowerCase().includes(searchItem.toLowerCase()), ), [searchItem], ); return (
<input
type="text"
placeholder="Search"
value={searchItem}
onChange={(e) => setSearchItem(e.target.value)}
/>
);
}
```
**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/react-search-list-u1s8b?file=/src/index.js)**
-
{searchResults.map((item) => (
<li key={item}>{item}</li>
))}
Answer
```js import { useState } from "react"; function fizzBuzz(n: number): string | number { if (n % 15 === 0) return "FizzBuzz"; if (n % 3 === 0) return "Fizz"; if (n % 5 === 0) return "Buzz"; return n; } export default function FizzBuzz() { const [count, setCount] = useState(1); return (React Fizz Buzz Program
Counting incrementally, replacing any number divisible by three with the word “fizz”, and any number divisible by five with the word “buzz”.{fizzBuzz(count)}
<button onClick={() => setCount((c) => Math.max(1, c - 1))}>-</button> <button onClick={() => setCount((c) => c + 1)}>+</button>Answer
**1. Using React.forwardRef():** ```js import { forwardRef, useRef, useImperativeHandle } from "react"; const Child = forwardRef((props, ref) => { useImperativeHandle(ref, () => ({ getMessage() { alert("Message from Child"); }, })); returnChild Component
; }); const Parent = () => { const childRef = useRef(); return (
<Child ref={childRef} />
<button onClick={() => childRef.current.getMessage()}>Click</button>
);
};
```
**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/react-forwardref-3serh?file=/src/index.js)**
**2. Using Class Component:**
```js
class Parent extends React.Component {
constructor(props) {
super(props);
this.child = React.createRef();
}
onClick = () => {
this.child.current.getMessage();
};
render() {
return (
<Child ref={this.child} />
<button onClick={this.onClick}>Click</button>
);
}
}
class Child extends React.Component {
getMessage() {
alert("Message from Child");
}
render() {
return Child Component
; } } ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/react-createref-t0gud?file=/src/index.js)** **3. Using callback Ref API:** ```js class Parent extends React.Component { render() { return (
<Child
ref={(instance) => {
this.child = instance;
}}
/>
<button
onClick={() => {
this.child.getMessage();
}}
>
Click
</button>
);
}
}
class Child extends React.Component {
getMessage() {
alert("Message from Child");
}
render() {
return Child Component
; } } ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/react-callback-ref-api-kp30y?file=/src/index.js)**Answer
```js import { useState } from "react"; export default function App() { const [show, setShow] = useState(true); return (
<button onClick={() => setShow((prev) => !prev)}>
Toggle: {show ? "Hide" : "Show"}
</button>
{show &&
);
}
```
**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/react-toggle-gipub?file=/src/App.js)**
Hello World!
}Answer
**Using function as a Prop:** ```js import { useState } from "react"; function Child({ text, onUpdate }: Readonly<{ text: string; onUpdate: (value: string) => void }>) { return ( <button onClick={() => onUpdate("Parent State Changed")}>{text}</button> ); } export default function Parent() { const [text, setText] = useState("Click Me!"); return <Child text={text} onUpdate={setText} />; } ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/react-function-as-a-prop-2unfh?file=/src/App.js)**Answer
```js import React, { Component } from "react"; import logo from "./react_photo-goose.jpg"; export default class Header extends Component { render() { return (
<img src={logo} width="100%" alt="Googe Pic" />
Answer
Accessing child state via ref is an anti-pattern — state should be lifted to the parent. When you genuinely need to call a method on a child (e.g. focus an input, trigger an animation), use **useImperativeHandle** and **forwardRef**: ```js import { forwardRef, useImperativeHandle, useRef, useState } from "react"; const Child = forwardRef(function Child(_, ref) { const [value, setValue] = useState(""); useImperativeHandle(ref, () => ({ getValue: () => value, })); return <input value={value} onChange={(e) => setValue(e.target.value)} />; }); export default function Parent() { const childRef = useRef < { getValue: () => string } > null; return ( <> <Child ref={childRef} /> <button onClick={() => alert(childRef.current?.getValue())}>Read</button> </> ); } ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/access-child-state-p2iip?file=/src/App.js)**Answer
**event.target.getAttribute:** ```js export default function Header() { const handleClick = (event: React.MouseEventAnswer
```js import { useState } from "react"; function Counter({ onIncrement, count, }: Readonly<{ onIncrement: () => void; count: number }>) { return (
<button onClick={onIncrement}>CLICK ME</button>
);
}
export default function App() {
const [count, setCount] = useState(1);
return <Counter count={count} onIncrement={() => setCount((c) => c + 1)} />;
}
```
**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/react-change-state-by-props-phjde?file=/src/index.js)**
{count}
Answer
```js import { useState } from "react"; type User = { id: number; name: string }; const initialUsers: User[] = [ { id: 101, name: "Tanu Kanda" }, { id: 102, name: "Sathwik Bhatti" }, { id: 103, name: "Vritika Nath" }, { id: 104, name: "Chanda Mittal" }, { id: 105, name: "Sumati Pau" }, ]; export default function ListComponent() { const [users, setUsers] = useState<User[]>(initialUsers); const deleteById = (id: number) => setUsers((prev) => prev.filter((user) => user.id !== id)); return (Delete an item from state array
-
{users.map((user) => (
<li key={user.id}>
<button onClick={() => deleteById(user.id)}>X - </button>
{user.name}
</li>
))}
Error: {error}
; if (!data) returnLoading…
; return{JSON.stringify(data, null, 2)};
}
```
## Q. Pass props in Link react-router
**render props:**
```js
import { BrowserRouter as Router, Link, Route, Routes } from "react-router-dom";
function IndexPage() {
return Home Page
; } function PropsPage({ title }: Readonly<{ title: string }>) { return{title}
; } export default function App() { return (
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button disabled={email.length < 1}>Submit</button>
);
}
```
**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/react-disable-a-button-yb8gm?file=/src/App.js)**
## Q. Update style of a component onScroll in React.js
```js
import { useState, useRef, useCallback } from "react";
const ITEMS = Array.from(
{ length: 50 },
() => "Get the scroll position on scroll in react.",
);
const containerStyle = { height: 300, overflowY: "scroll" } as const;
export default function App() {
const prevScrollY = useRef(0);
const [goingUp, setGoingUp] = useState(false);
const onScroll = useCallback(
(e: React.UIEvent
<input id={id} type="checkbox" />
<label htmlFor={id}>label</label>
);
}
```
**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/generate-unique-id-for-form-e7iqz?file=/src/App.js)**
## Q. How can one tell the version of React running at runtime in the browser?
**version Hook**
```js
import { version } from "react";
export default function App() {
return (
React version: {version}
Current Time: {time}
; } ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/update-component-every-second-i0gk5?file=/src/App.js)** ## Q. How to declare a global variable in React? **Window Object:** ```js const name = "Hello React"; export default function App() { return (Global variable using window object
{name}
State variable: {stateValue}
<button onClick={handleIncrementRef}>Increment Ref (no re-render)</button> <button onClick={() => setStateValue((v) => v + 1)}> Increment State (re-renders) </button>-
{posts.map((post) => (
<li key={post.id}>
<a href={`/posts/${post.id}`}>{post.title}</a>
</li>
))}
<button onClick={() => setGood((v) => !v)}>
);
}
```
**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/toggle-boolean-state-in-react-kguly?file=/src/index.js)**
## Q. Dynamically add child components in React
```js
// Parent.js
export default class Parent extends React.Component {
render() {
return (
<>
Do you feel good today?
<span role="img" aria-label={good ? "Thumbs Up" : "Thumbs Down"}>
{good ? "Yes! 👍" : "No! 👎"}
</span>
</button>
Parent Component!
{this.props.children} </> ); } } ``` ```js // Child.js export default class Child extends React.Component { render() { return ( <>Child Component!
</> ); } } ``` ```js // index.js import Parent from "./Parent"; import Child from "./Child"; const rootElement = document.getElementById("root"); ReactDOM.render(Login
<button onClick={onLogin}>Log in</button>Dashboard (protected)
<button onClick={onLogout}>Log out</button>File Upload in React
<input type="file" name="file" onChange={(e) => { fileRef.current = e.target.files?.[0] ?? null; }} /> <button onClick={handleUpload}>Upload</button>{value}
</> ); } ``` **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/react-search-using-settimeout-9d8vd?file=/src/App.js)** ## Q. How to implement default or NotFound page? ```js import { Link, BrowserRouter as Router, Route, Routes } from "react-router-dom"; const IndexPage = () =>Home Page
; const AboutPage = () =>About Page
; const NoMatchPage = () =>Page Not Found
; export default function App() { return ({count}
<button onClick={() => setCount((c) => c + 1)}>Increment</button> <button onClick={() => setCount((c) => c - 1)}>Decrement</button> <button onClick={() => setCount(0)}>Reset</button> </> ); } ``` ```js // Counter.test.js import { render, screen, fireEvent } from "@testing-library/react"; import Counter from "./page"; describe("Counter", () => { it("renders with initial count of 0", () => { render(React Font Awesome Icons
SVG in React
<img
src={"http://s.cdpn.io/3/kiwi.svg"}
alt="Kiwi Bird"
width="200px"
height="200px"
/>
Repeat an element n times using JSX
{Array.from({ length: 5 }, (_, i) => (
<div key={i}>
Field {i}:
))}
</div>
</>
);
}
```
**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/repeat-an-element-n-times-using-jsx-ze1yh?file=/src/App.js)**
## Q. How can I set a cookie in react?
```js
import { CookiesProvider } from "react-cookie";
import { createRoot } from "react-dom/client";
import App from "./App";
const rootElement = document.getElementById("root");
createRoot(rootElement).render(
Cookies in React
<input placeholder="Cookie value" value={name} onChange={(e) => setName(e.target.value)} /> <button onClick={handle}>Set Cookie</button> {cookies.name &&Cookies Value: {cookies.name}
}
</>
);
};
export default App;
```
**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/repeat-an-element-n-times-using-jsx-ze1yh?file=/src/App.js)**
## Q. How to Create dependent dropdowns that populates data with each other in React.js?
```js
/**
* Dependent Dropdown in React
*/
import { useState } from "react";
const data = [
{ name: "Delhi", cities: ["Siri", "Sultanpur", "Tughlqabad", "Jahanpanah", "Firozobad"] },
{ name: "Maharashtra", cities: ["Mumbai", "Pune", "Nagpur", "Thane", "Nashik", "Jalgaon"] },
{ name: "West Bengal", cities: ["Kolkata", "Asansol", "Siliguri", "Durgapur", "Baharampur"] },
{ name: "Tamil Nadu", cities: ["Chennai", "Coimbatore", "Madurai", "Tiruchirappalli"] },
];
export default function App() {
const [capital, setCapital] = useState("");
const [cities, setCities] = useState<string[]>([]);
const [city, setCity] = useState("");
function updateSelect(e: React.ChangeEvent
<section
aria-label="Slideshow"
className={`relative w-full max-w-2xl rounded-2xl overflow-hidden shadow-xl ${slides[current].bg} text-white transition-colors duration-500`}
>
);
}
```
## Q. Create a custom useFetch hook in React?
{slides[current].title}
{slides[current].description}
{slides.map((slide, i) => (
<button
key={slide.id}
onClick={() => setCurrent(i)}
aria-label={`Go to slide ${i + 1}`}
className={`w-2.5 h-2.5 rounded-full transition-colors ${
i === current ? "bg-white" : "bg-white/40"
}`}
/>
))}
</section>
{current + 1} / {slides.length}
Answer
```js import { useEffect, useReducer } from "react"; type StateLoading…
; if (error) returnError: {error}
; return (-
{data?.map((user) => (
<li key={user.id}>{user.name} — {user.email}</li>
))}
Answer
```js import { useMemo, useState } from "react"; const TOTAL_ITEMS = 100; const PAGE_SIZE = 10; function usePagination(total: number, pageSize: number) { const [page, setPage] = useState(1); const totalPages = Math.ceil(total / pageSize); const items = useMemo(() => { const start = (page - 1) * pageSize + 1; const end = Math.min(page * pageSize, total); return Array.from({ length: end - start + 1 }, (_, i) => start + i); }, [page, pageSize, total]); return { page, totalPages, items, setPage }; } export default function App() { const { page, totalPages, items, setPage } = usePagination(TOTAL_ITEMS, PAGE_SIZE); return ( <>Pagination
-
{items.map((n) => <li key={n}>Item {n}</li>)}
Page {page} of {totalPages}
</> ); } ```Answer
```js import { useState } from "react"; type StarRatingProps = Readonly<{ maxStars?: number; onChange?: (rating: number) => void; }>; function StarRating({ maxStars = 5, onChange }: StarRatingProps) { const [rating, setRating] = useState(0); const [hover, setHover] = useState(0); const handleSelect = (value: number) => { setRating(value); onChange?.(value); }; return ( <div style=> {Array.from({ length: maxStars }, (_, i) => i + 1).map((star) => ( <button key={star} aria-label={`${star} star${star > 1 ? "s" : ""}`} onClick={() => handleSelect(star)} onMouseEnter={() => setHover(star)} onMouseLeave={() => setHover(0)} style= > ★ </button> ))} <span style=> {rating > 0 ? `${rating} / ${maxStars}` : "No rating"} </span> </div> ); } export default function App() { return ( <div style=>Rate this product
<StarRating onChange={(r) => console.log("Rating:", r)} /> </div> ); } ```Answer
```js import { useState, useEffect } from "react"; function useLocalStoragePersisted Input
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name (saved to localStorage)" />Hello, {name || "stranger"}!
Answer
```js import { useState, useEffect, useRef, useCallback } from "react"; const PAGE_SIZE = 20; function generateItems(page: number) { return Array.from({ length: PAGE_SIZE }, (_, i) => ({ id: (page - 1) * PAGE_SIZE + i + 1, text: `Item ${(page - 1) * PAGE_SIZE + i + 1}`, })); } export default function App() { const [items, setItems] = useState(generateItems(1)); const [page, setPage] = useState(1); const [loading, setLoading] = useState(false); const loaderRef = useRefInfinite Scroll (page {page})
-
{items.map((item) => <li key={item.id}>{item.text}</li>)}
Answer
```js import { useState, useTransition, useMemo } from "react"; const ALL_ITEMS = Array.from({ length: 10_000 }, (_, i) => `Item ${i + 1}`); export default function App() { const [query, setQuery] = useState(""); const [filterQuery, setFilterQuery] = useState(""); const [isPending, startTransition] = useTransition(); const filtered = useMemo( () => ALL_ITEMS.filter((item) => item.toLowerCase().includes(filterQuery.toLowerCase())), [filterQuery] ); const handleChange = (e: React.ChangeEventuseTransition Demo
<input value={query} onChange={handleChange} placeholder="Filter 10,000 items…" /> {isPending && <p style=>Updating list…</p>}-
{filtered.slice(0, 100).map((item) => <li key={item}>{item}</li>)}
Answer
```js import { useState } from "react"; type FormValues = { name: string; email: string; password: string }; type FormErrors = Partial<Record<keyof FormValues, string>>; function validate(values: FormValues): FormErrors { const errors: FormErrors = {}; if (!values.name.trim()) errors.name = "Name is required."; if (!values.email.includes("@")) errors.email = "Enter a valid email."; if (values.password.length < 8) errors.password = "Password must be at least 8 characters."; return errors; } export default function SignupForm() { const [values, setValues] = useStateForm submitted successfully!
; return ( <form onSubmit={handleSubmit} noValidate style=>Sign Up
{(["name", "email", "password"] as const).map((field) => ( <div key={field}> {errors[field] && <p style=>{errors[field]}</p>} </div> ))} </form> ); } ``` </details> ## Q. How to implement drag and drop list in React?Answer
```js import { useState, useRef, type DragEvent } from "react"; const initialItems = ["Task A", "Task B", "Task C", "Task D", "Task E"]; export default function DragDropList() { const [items, setItems] = useState(initialItems); const dragIndex = useRef<number | null>(null); const handleDragStart = (index: number) => { dragIndex.current = index; }; const handleDrop = (dropIndex: number) => { if (dragIndex.current === null || dragIndex.current === dropIndex) return; const updated = [...items]; const [dragged] = updated.splice(dragIndex.current, 1); updated.splice(dropIndex, 0, dragged); setItems(updated); dragIndex.current = null; }; return ( <div style=>Drag & Drop List
<ul style=> {items.map((item, index) => ( <li key={item} draggable onDragStart={() => handleDragStart(index)} onDragOver={(e: DragEvent) => e.preventDefault()} onDrop={() => handleDrop(index)} style= > ☰ {item} </li> ))} </ul> </div> ); } ```
## [Slideshow App](https://github.com/hackerrank-test/hackerrank-react-slideshow-app)
## [Catalog Viewer](https://github.com/hackerrank-test/hackerrank-react-catalog-viewer)