ReactJS : Practice Set 4

Rahul Kumar
10 min readMar 11, 2024

All about useState hook in React.

Q 1. Given an array of characters, build a Tab component in React that shows the name of characters on click of two buttons, one for heroes and other for villains. On click of “Show Heroes” button, a list of heroes should be displayed and on click of “Show Villains” button, a list of villains should be displayed on the DOM. [Use useState Hook]

Data:

const characters = {
heroes: [
{
name: "IRON MAN",
powers: "Genius,Rich,IRON Suit",
costume: "IRON MAN suit",
},
{
name: "ANT MAN",
powers: "Ant man suit",
costume: "Ant man suit",
},
{
name: "Spider-man",
powers: "Reflexes,Speed,Spider-Sense",
costume: "Spider Suit",
},
{
name: "Bat man",
powers: "Rich,Bat suit",
costume: "Bat Suit",
},
{
name: "Super-man",
powers: "Superhuman strength,Reflexes,Speed",
costume: "Superman Suit",
},
],
villains: [
{
name: "Thanos",
powers: "Superhuman strength,Reflexes,Speed,",
costume: "Metal armor",
},
{
name: "Venom",
powers: "shapeshifting and camouflage Symbiotes autonomous defense",
costume: "black suit",
},
{
name: "Kang the conqueror",
powers: "time travel, can access all tech",
costume: "kang armor",
},
{
name: "Joker",
powers: "clownlike appearance and sick humour",
costume: "Joker costume",
},
],
};

On Render:

After clicking on show Heros:

After clicking on show Villains:

Solution:

CharacterComp.jsx

import React, { useState } from "react";

const CharacterComp = ({ characters }) => {
const [data, setData] = useState([]);
const [header, setHeader] = useState("");

const { heroes, villains } = characters;

{
console.log(data);
}
return (
<>
<div>
<button
style={{ padding: "10px", fontSize: "20px", margin: "10px" }}
onClick={() => {
setData(heroes);
setHeader("Heroes:");
}}
>
Show Heros
</button>
<button
style={{ padding: "10px", fontSize: "20px", margin: "10px" }}
onClick={() => {
setData(villains);
setHeader("Villains:");
}}
>
Show Villains
</button>

<div>
<h1>{header}</h1>
{data.map(({ name, powers, costume }) => {
return (
<div>
<h1>{name}</h1>
<p>{powers}</p>
<p>{costume}</p>
</div>
);
})}
</div>
</div>
</>
);
};

export default CharacterComp;

App.jsx

import React from "react";
import "./App.css";

import CharacterComp from "./components/CharacterComp";

const characters = {
heroes: [
{
name: "IRON MAN",
powers: "Genius,Rich,IRON Suit",
costume: "IRON MAN suit",
},
{
name: "ANT MAN",
powers: "Ant man suit",
costume: "Ant man suit",
},
{
name: "Spider-man",
powers: "Reflexes,Speed,Spider-Sense",
costume: "Spider Suit",
},
{
name: "Bat man",
powers: "Rich,Bat suit",
costume: "Bat Suit",
},
{
name: "Super-man",
powers: "Superhuman strength,Reflexes,Speed",
costume: "Superman Suit",
},
],
villains: [
{
name: "Thanos",
powers: "Superhuman strength,Reflexes,Speed,",
costume: "Metal armor",
},
{
name: "Venom",
powers: "shapeshifting and camouflage Symbiotes autonomous defense",
costume: "black suit",
},
{
name: "Kang the conqueror",
powers: "time travel, can access all tech",
costume: "kang armor",
},
{
name: "Joker",
powers: "clownlike appearance and sick humour",
costume: "Joker costume",
},
],
};

function App() {
return (
<>
<CharacterComp characters={characters} />
</>
);
}

export default App;

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Q2. Build a React component with two buttons + and which increases/decreases the font size of a heading text “Welcome” by 1px. Keep the initial font size to 18px.[ Use useState Hook.]

Output:

Solution:

SizeChanger.jsx

import React, { useState } from "react";

const SizeChanger = () => {
const [fontSize, setFontSize] = useState(18);
return (
<>
<div style={{ fontSize: `${fontSize}px` }}>Welcome</div>

<button
style={{
margin: "10px",
padding: "5px",
fontSize: "15px",
width: "50px",
}}
onClick={() => {
setFontSize(fontSize - 1);
}}
>
-
</button>
<button
style={{
margin: "10px",
padding: "5px",
fontSize: "15px",
width: "50px",
}}
onClick={() => {
setFontSize(fontSize + 1);
}}
>
+
</button>
</>
);
};

export default SizeChanger;

App.jsx

import React from "react";
import "./App.css";

import SizeChanger from "./components/SizeChanger";

function App() {
return (
<>
<SizeChanger />
</>
);
}

export default App;

Q3. Given an array of items:

const itemList = [
{ id: 1, name: "Apple", category: "Fruit" },
{ id: 2, name: "Carrot", category: "Vegetable" },
{ id: 3, name: "Banana", category: "Fruit" },
{ id: 4, name: "Broccoli", category: "Vegetable" },
];

A. Build a React component that displays a list of items. Display fruits in orange color and vegetables in green color.

B. Create two buttons to filter the items by their category using the useState hook

Solution:

ListFruitsAndVegetables.jsx

import React, { useState } from 'react'

const ListFruitsAndVegetables = ({itemList}) => {
const [data, SetData] = useState(itemList);
return (
<div>
<button style={{padding:"10px", fontSize:"18px", margin:"5px", }} onClick={()=>SetData(itemList)}>All</button>
<button style={{padding:"10px", fontSize:"18px", margin:"5px", }} onClick={()=>SetData(itemList.filter(({category})=> category === 'Fruit'))}>Fruits</button>
<button style={{padding:"10px", fontSize:"18px", margin:"5px", }} onClick={()=>SetData(itemList.filter(({category})=> category === 'Vegetable'))}>Vegetables</button>
<ul>
{
data.map(({name,id, category})=><li key={id} style={{color: category === "Fruit" ? "orange" : "green"}}>{name}</li>)
}
</ul>
</div>
)
}

export default ListFruitsAndVegetables;

App.jsx

import "./App.css";

import ListFruitsAndVegetables from "./components/ListFruitsAndVegetables";

const itemList = [
{ id: 1, name: "Apple", category: "Fruit" },
{ id: 2, name: "Carrot", category: "Vegetable" },
{ id: 3, name: "Banana", category: "Fruit" },
{ id: 4, name: "Broccoli", category: "Vegetable" },
];

function App() {
return <ListFruitsAndVegetables itemList={itemList} />;
}

export default App;

Q 4. Given an array of todoItems:

const todoItems = [
{id: 1, task: "Writing 1-page poem", isDone: true},
{id: 2, task: "Gym", isDone: false},
{id: 3, task: "Shopping", isDone: false},
{id: 4, task: "Standup call", isDone: true},
]

a. Build a React component that takes the todoItems as props and list all the todo tasks.

b. if isDone is true then show the item with a strikethrough

TodoStrikeThrough.jsx

import React from "react";

const TodoStrikeThrough = ({ todoItems }) => {
return (
<div>
<h1>Todo List</h1>
<ul>
{todoItems.map(({ id, task, isDone }) => {
return (
<li
key={id}
style={{ textDecoration: isDone ? "line-through" : "" }}
>
{task}
</li>
);
})}
</ul>
</div>
);
};

export default TodoStrikeThrough;

App.jsx

import "./App.css";

import TodoStrikeThrough from "./components/TodoStrikeThrough";

const todoItems = [
{ id: 1, task: "Writing 1-page poem", isDone: true },
{ id: 2, task: "Gym", isDone: false },
{ id: 3, task: "Shopping", isDone: false },
{ id: 4, task: "Standup call", isDone: true },
];

function App() {
return <TodoStrikeThrough todoItems={todoItems} />;
}

export default App;

c. Add a X button against each item and remove that task from the list on click of the button.

TodoStrikeThroughWithCross.jsx

import React, { useState } from "react";

const TodoStrikeThroughWithCross = ({ todoItems }) => {
const [todoList, setTodoList] = useState(todoItems);
return (
<div>
<h1>Todo List</h1>
<ul>
{todoList.map(({ id, task, isDone }) => {
return (
<li
key={id}
style={{ textDecoration: isDone ? "line-through" : "" }}
>
{task}
<button onClick={() => setTodoList(todoList.filter((todo)=> todo.id !== id))}>X</button>
</li>
);
})}
</ul>
</div>
);
};

export default TodoStrikeThroughWithCross;

App.jsx

import "./App.css";

import TodoStrikeThroughWithCross from "./components/TodoStrikeThroughWithCross";

const todoItems = [
{ id: 1, task: "Writing 1-page poem", isDone: true },
{ id: 2, task: "Gym", isDone: false },
{ id: 3, task: "Shopping", isDone: false },
{ id: 4, task: "Standup call", isDone: true },
];

function App() {
return <TodoStrikeThroughWithCross todoItems={todoItems} />;
}

export default App;

Q 5. Given an array of todoItems:

const todoItems = [
{id: 1, task: "Writing 1-page poem", isDone: false},
{id: 2, task: "Gym", isDone: false},
{id: 3, task: "Shopping", isDone: false},
{id: 4, task: "Standup call", isDone: false},
]

A. Build a React component that takes the todoItems as props and list all the todo tasks.

TodoMarkDone.jsx

import React from "react";

const TodoMarkDone = ({ todoItems }) => {
return (
<div>
<h1>Todo List</h1>
<ul style={{listStyle:"none"}}>
{todoItems.map(({ id, task, isDone }) => {
return (
<li key={id}>
{task}
<button>Mark as done</button>
</li>
);
})}
</ul>
</div>
);
};

export default TodoMarkDone;

App.jsx

import "./App.css";

import TodoMarkDone from "./components/TodoMarkDone";

const todoItems = [
{ id: 1, task: "Writing 1-page poem", isDone: true },
{ id: 2, task: "Gym", isDone: false },
{ id: 3, task: "Shopping", isDone: false },
{ id: 4, task: "Standup call", isDone: true },
];

function App() {
return <TodoMarkDone todoItems={todoItems} />;
}

export default App;

B. Add a “Mark as Done” button against each item and toggle isDone property value between true and false on click of the button. If isDone is true change the color of that task to red with a strikethrough and if it is false remove the strikethrough and the red color.

TodoMarkDone.jsx

import React, { useState } from "react";

const TodoMarkDone = ({ todoItems }) => {
const [todoList, setTodoList] = useState(todoItems);
return (
<div>
<h1>Todo List</h1>
<ul style={{ listStyle: "none" }}>
{todoList.map(({ id, task, isDone }) => {
return (
<li
key={id}
style={
isDone ? { textDecoration: "line-through", color: "red" } : {}
}
>
{task}
<button
onClick={() => {
const updatedTodoList = todoList.map((todo) =>
todo.id === id ? { ...todo, isDone: !todo.isDone } : todo
);
setTodoList(updatedTodoList);
}}
>
Mark as done
</button>
</li>
);
})}
</ul>
</div>
);
};

export default TodoMarkDone;

App.jsx

import "./App.css";

import TodoMarkDone from "./components/TodoMarkDone";

const todoItems = [
{ id: 1, task: "Writing 1-page poem", isDone: true },
{ id: 2, task: "Gym", isDone: false },
{ id: 3, task: "Shopping", isDone: false },
{ id: 4, task: "Standup call", isDone: true },
];

function App() {
return <TodoMarkDone todoItems={todoItems} />;
}

export default App;

Q6. Given an array of books:

const books = [
{
id: 1,
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
genre: "Classic",
},
{
id: 2,
title: "To Kill a Mockingbird",
author: "Harper Lee",
genre: "Classic",
},
{
id: 3,
title: "The Catcher in the Rye",
author: "J.D. Salinger",
genre: "Classic",
},
{ id: 4, title: "1984", author: "George Orwell", genre: "Dystopian" },
{
id: 5,
title: "Brave New World",
author: "Aldous Huxley",
genre: "Dystopian",
},
{
id: 6,
title: "The Hunger Games",
author: "Suzanne Collins",
genre: "Young Adult",
},
{
id: 7,
title: "Harry Potter and the Philosopher's Stone",
author: "J.K. Rowling",
genre: "Young Adult",
},
];

a. Build a React component that displays the title and author of each book.

b. Add buttons to filter the books by genre using the useState hook.

BooksStore.jsx

import React, { useState } from "react";

const BooksStore = ({ books }) => {
const [bookList, SetBookList] = useState(books);
return (
<div>
<button
onClick={() => {
SetBookList(books);
}}
>
All Genres
</button>
<button
onClick={() => {
SetBookList(
books.filter((book) => (book.genre === "Classic")));
}}
>
Classics
</button>
<button
onClick={() => {
SetBookList(
books.filter(({ genre }) => genre === "Dystopian"));
}}
>
Dystopian
</button>
<button
onClick={() => {
SetBookList(
books.filter(({ genre }) => genre === "Young Adult"));
}}
>
Young Adult
</button>
{
console.log(bookList)
}
{bookList.map(({ id, title, author }) => {
return (
<div key={id}>
<h2 style={{ fontSize: "25px" }}>{title}</h2>
<p style={{ fontSize: "18px" }}>{author}</p>
</div>
);
})}
</div>
);
};

export default BooksStore;

App.jsx

import "./App.css";
import BooksStore from "./components/BooksStore";


const books = [
{
id: 1,
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
genre: "Classic",
},
{
id: 2,
title: "To Kill a Mockingbird",
author: "Harper Lee",
genre: "Classic",
},
{
id: 3,
title: "The Catcher in the Rye",
author: "J.D. Salinger",
genre: "Classic",
},
{ id: 4, title: "1984", author: "George Orwell", genre: "Dystopian" },
{
id: 5,
title: "Brave New World",
author: "Aldous Huxley",
genre: "Dystopian",
},
{
id: 6,
title: "The Hunger Games",
author: "Suzanne Collins",
genre: "Young Adult",
},
{
id: 7,
title: "Harry Potter and the Philosopher's Stone",
author: "J.K. Rowling",
genre: "Young Adult",
},
];

function App() {
return <BooksStore books={books} />
}

export default App;

Q 7. Build a game component in React where the player has a certain number of lives. Display the current number of lives and allows the player to decrement the number of lives by one with a button click. Once the number of lives reaches zero, display a “Game Over” message.

GameOfLife.jsx

import React, { useState } from "react";

const GameOfLife = () => {
const [lives, setLives] = useState(Math.floor(Math.random() * 10));
return (
<div>
<h1>Current Lives: {lives}</h1>
<button
onClick={() => {
setLives(lives - 1);
}}
disabled={lives === 0}
>
Lose a life
</button>
{lives === 0 ? <h2>Game Over</h2> : " "}
</div>
);
};

export default GameOfLife;

App.jsx

import "./App.css";

import GameOfLife from "./components/GameOfLife";

function App() {
return <GameOfLife />;
}
export default App;

Output:

Thanks…

--

--