Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useEffect, useState } from "react";
- import { Box } from "@mui/material";
- export default function Cart() {
- const [items, setItems] = useState(["Book 1", "Book 2"]);
- const [quantities, setQuantities] = useState({});
- const [cart, setCart] = useState([]);
- useEffect(() => {
- console.log("quantities", quantities);
- }, [quantities]);
- useEffect(() => {
- console.log("cart", cart);
- }, [cart]);
- const addToCart = (item, quantity = 1) => {
- console.log(item, quantity);
- const index = cart.findIndex(cartItem => cartItem.name === item);
- let newCart = [...cart];
- if (index > -1) {
- newCart.splice(index, 1, { ...newCart[index], quantity: newCart[index]["quantity"] + quantity });
- // newCart = [
- // ...newCart.slice(0, index),
- // { ...newCart[index], quantity: newCart[index]["quantity"] + quantity },
- // ...newCart.slice(index + 1)
- // ];
- } else {
- newCart = [...newCart, { name: item, quantity: quantity }]
- }
- setCart(newCart);
- }
- return (
- <div style={{display: "flex", justifyContent: "center", alignItems: "center", height: "80vh"}}>
- <div
- // style={{ alignContent: "center"}}
- >
- {
- items.map(item => <div key={`item$${item}`}
- // style={{ display: "flex", alignItems: "center", height: "400px"}}
- >
- <label>{item}</label>
- <input type="number" value={quantities[item] ? parseInt(quantities[item]) : 1} onChange={e => setQuantities({ ...quantities, [item]: parseInt(e.target.value) })} />
- <button onClick={() => addToCart(item, quantities[item])}>{"Add to cart"}</button>
- </div>)
- }
- </div>
- </div>
- // <div>
- // {
- // items.map(item => (
- // <div key={item}>
- // <label>{item}</label>
- // <input
- // type="number"
- // value={quantities[item] !== undefined ? quantities[item] : 0}
- // onChange={e => {
- // let value = e.target.value;
- // // Use regex to remove leading zeros
- // let cleanedValue = value.replace(/^0+(?=\d)/, '');
- // // Handle empty input
- // setQuantities({ ...quantities, [item]: cleanedValue === '' ? '' : cleanedValue });
- // }}
- // />
- // </div>
- // ))
- // }
- // </div>
- );
- }
- import React, { useEffect, useState } from 'react';
- function List(props) {
- const [list, setList] = useState([
- { n: 'diary', s: 5 },
- { n: 'hat', s: 3 },
- ]);
- const [cart, setCart] = useState([]);
- const add = (item, qty = 1) => {
- const newC = [...cart];
- const ind = newC.findIndex((c) => c.n == item);
- if (ind > -1) {
- newC.splice(ind, 1, { n: item, s: newC[ind].s + qty });
- setCart(newC);
- } else {
- setCart([...newC, { n: item, s: qty }]);
- }
- };
- const remove = (item, qty = 1) => {
- const newC = [...cart];
- const ind = newC.findIndex((c) => c.n == item);
- if (newC[ind].s > 1) {
- newC.splice(ind, 1, { n: item, s: newC[ind].s - qty });
- setCart(newC);
- } else {
- setCart(newC.filter((c) => c.n !== item));
- }
- };
- useEffect(() => {
- console.log(cart);
- }, [cart]);
- return (
- <div
- style={{
- display: 'flex',
- flexDirection: 'row',
- justifyContent: 'space-between',
- }}
- >
- <div
- style={{
- display: 'flex',
- flexDirection: 'column',
- justifyContent: 'space-between',
- }}
- >
- {list.map((item) => (
- <div style={{ display: 'flex', flexDirection: 'row' }}>
- <div>{item.n}</div>
- <button
- disabled={
- item.s < 1 || cart?.filter((c) => c.n == item.n)[0]?.s == item.s
- }
- onClick={() => add(item.n)}
- >
- {'+'}
- </button>
- </div>
- ))}
- </div>
- <div
- style={{
- display: 'flex',
- flexDirection: 'column',
- justifyContent: 'space-between',
- }}
- >
- {cart?.map((item) => (
- <div style={{ display: 'flex', flexDirection: 'row' }}>
- <div>{`${item.n}: ${item.s}`}</div>
- <button onClick={() => remove(item.n)}>{'-'}</button>
- </div>
- ))}
- </div>
- </div>
- );
- }
- export default List;
- import React from 'react';
- const PageComponent = React.memo(({ data }) => {
- return (
- <div>
- {data}
- </div>
- );
- });
- const App = () => {
- const [pages, setPages] = useState([]);
- const handleLoadMore = () => {
- // Fetch more data and update the pages state
- };
- return (
- <div>
- {pages.map((page, index) => (
- <PageComponent key={index} data={page} />
- ))}
- <button onClick={handleLoadMore}>Load More</button>
- </div>
- );
- };
- import { useEffect, useState } from "react";
- import { Box } from "@mui/material";
- const PageComponent = React.memo( ({ data }) => {
- return (
- <div>
- {/* Render page content using data */}
- </div>
- );
- });
- export default function Solution() {
- const [data, setData] = useState([]);
- const [dataWithImages, setDataWithImages] = useState([]);
- const [error, setError] = useState('');
- const [loading, setLoading] = useState(true);
- const [hoverIndex, setHoverIndex] = useState(null);
- const fetchData = async (url) => {
- try {
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error(`Response status: ${response.status}`);
- }
- const data = await response.json();
- return data;
- } catch (error) {
- setError(error);
- } finally {
- setLoading(false);
- }
- };
- const fetchAllData = async (items) => {
- try {
- const promises = items?.map((item) =>
- fetchData(`https://dog.ceo/api/breed/${item}/images/random`)
- );
- const imagesData = await Promise.all(promises);
- return imagesData;
- } catch (error) {
- setError(error);
- }
- };
- useEffect(() => {
- fetchData('https://dog.ceo/api/breeds/list/all').then((data) => {
- setData(data.message);
- fetchAllData(Object.keys(data?.message)).then((dataArray) => {
- setDataWithImages(dataArray);
- setLoading(false);
- });
- });
- }, []);
- return (
- <>
- {loading && <div id={'js_loading'}>{'Loading'}</div>}
- {!loading && data && dataWithImages && (
- <div style={{ display: 'flex', flexWrap: 'wrap' }} id={'js_gallery'}>
- {dataWithImages &&
- Array.isArray(dataWithImages) &&
- dataWithImages.map((imgObj, index) => (
- <div
- style={{ position: 'relative', maxHeight: '200px' }}
- id={'js_gallery'}
- onMouseEnter={() => setHoverIndex(index)}
- onMouseLeave={() => setHoverIndex(null)}
- >
- <img
- src={imgObj.message}
- style={{ maxHeight: '200px', objectFit: 'cover' }}
- className={'js_image'}
- />
- <div
- className={'js_name'}
- style={{
- position: 'absolute',
- left: '10px',
- bottom: '10px',
- zIndex: 400,
- color: 'white',
- textShadow: '2px 2px 5px black',
- opacity: hoverIndex == index ? 1 : 0,
- }}
- id={'js_gallery'}
- >
- {Object.keys(data)[index]
- ? Object.keys(data)[index]?.charAt(0)?.toUpperCase() +
- Object.keys(data)[index]?.slice(1)
- : 'Good Dog'}
- </div>
- </div>
- ))}
- </div>
- )}
- </>
- );
- }
- import React, { useEffect, useState } from "react";
- import IconButton from '@mui/material/IconButton';
- import DeleteIcon from '@mui/icons-material/Delete';
- export default function Solution() {
- const [data, setData] = React.useState([]);
- const [error, setError] = React.useState('');
- const [deleteError, setDeleteError] = React.useState('');
- const [token, setToken] = React.useState(typeof window !== 'undefined' ? localStorage.getItem('token') : null);
- const fetchData = async (url) => {
- try {
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error();
- }
- const data = await response.json();
- setData(data);
- } catch (error) {
- setError(error);
- }
- };
- const deleteData = async (id) => {
- try {
- const response = await fetch(
- 'https://api.sampleapis.com/countries/countries',
- {
- method: 'POST',
- headers: {
- // Accept: 'application/json',
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${token}`,
- },
- body: JSON.stringify({ id: id }),
- }
- );
- const data = await response.json();
- if (data.error != 200) {
- setDeleteError(data.message);
- }
- console.log(data);
- } catch (error) {
- setError(error);
- }
- };
- React.useEffect(() => {
- fetchData('https://api.sampleapis.com/countries/countries');
- setToken(localStorage.getItem('token'));
- }, []);
- const deleteCountry = (id) => {
- deleteData(id);
- };
- return (
- <div>
- <h1 style={{margin: "20px 0"}}>Countries</h1>
- <h5 style={{ color: 'red', fontWeight: "300", margin: "20px 0" }}>{deleteError}</h5>
- <table
- // border={13}
- // cellPadding={5}
- // cellSpacing={1}
- // style={{ borderColor: '#fefefe', borderCollapse: "collapse" }}
- >
- <thead>
- <tr>
- <th>ID</th>
- <th>Name</th>
- <th>Currency</th>
- <th>Capital</th>
- <th>Action</th>
- </tr>
- </thead>
- <tbody>
- {data &&
- Array.isArray(data) &&
- data.map((country) => (
- <tr key={country.id}>
- <td>{country.id}</td>
- <td>{country.name}</td>
- <td>{country.currency}</td>
- <td>{country.capital}</td>
- <td>
- <IconButton aria-label="delete" onClick={() => deleteCountry(country.id)}>
- <DeleteIcon />
- </IconButton>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- );
- }
- import { useEffect, useState } from "react";
- import { Box } from "@mui/material";
- export default function Solution() {
- const [searchTerm, setSearchTerm] = useState("");
- const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
- const [similar, setSimilar] = useState(null);
- const fetchData = async (url) => {
- try {
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error();
- }
- const data = await response.json();
- return data;
- } catch (error) {
- setError(error);
- } finally {
- setLoading(false);
- }
- };
- // debounce
- useEffect(() => {
- const timeoutId = setTimeout(() => {
- fetchData('https://api.sampleapis.com/coffee/hot')
- .then(result => setData(result && Array.isArray(result) && result.filter((item) => item?.title?.toLowerCase().includes(searchTerm?.toLowerCase()))))
- }, 2000);
- return () => clearTimeout(timeoutId);
- }, [searchTerm]);
- const handleSearch = (e) => {
- setLoading(true);
- setSimilar(null);
- e.preventDefault();
- setSearchTerm(e.target.value);
- }
- const handleSuggestionClick = () => {
- fetchData('https://api.sampleapis.com/coffee/iced')
- .then(result => setSimilar(result && Array.isArray(result) ? result : []))
- }
- return (
- <Box>
- <div style={{ marginBottom: "5px" }}>Search Coffee Type (Ex: latte)</div>
- <input
- type="text"
- value={searchTerm}
- onChange={handleSearch}
- style={{
- width: "100%",
- border: "1px solid #d1d1d1",
- padding: "8px"
- }}
- />
- {loading &&
- <div style={{ margin: "5px 0" }}>Loading Suggestions...</div>
- }
- {
- !loading && !similar && data && Array.isArray(data) && data.map((item) => (
- <div
- key={item?.title}
- style={{
- marginTop: "3px",
- marginBottom: "3px",
- padding: "4px",
- background: "#f4f4f4",
- cursor: "pointer",
- }}
- onClick={handleSuggestionClick}
- >{item?.title}</div>
- ))
- }
- {similar && Array.isArray(similar) &&
- <>
- <div style={{ margin: "5px 0" }}>Similar Iced Coffee:</div>
- <div style={{ display: 'flex', flexWrap: 'wrap', marginTop: "3px", marginBottom: "3px", }}>
- {
- similar.map((item, index) => (
- <div
- style={{ position: 'relative', maxHeight: '200px' }}
- id={'js_gallery'}
- key={`js_gallery${index}`}
- >
- <img
- src={item.image}
- style={{ maxHeight: '200px', objectFit: 'cover' }}
- className={'js_image'}
- />
- <div
- className={'js_name'}
- style={{
- position: 'absolute',
- left: '10px',
- bottom: '10px',
- zIndex: 400,
- color: 'white',
- textShadow: '2px 2px 5px black',
- opacity: 1,
- }}
- id={'js_gallery'}
- >
- {item.title
- ? item.title
- : 'Iced Coffee'}
- </div>
- </div>
- ))
- }
- </div>
- </>
- }
- </Box>
- );
- }
- import { useEffect, useRef, useState, useCallback } from "react";
- import TypewriterLetter from "./TypewriterLetter";
- // This is considered a failure code response :)
- // this allows us to filter out nodes that
- // don't follow the pattern in O(1) notation
- const depthMap = {
- 0: "BODY",
- 1: "CODE",
- 2: "DIV",
- 3: "SPAN",
- 4: "I"
- };
- export default function App() {
- // use a ref here so we don't re-render every time
- // we iterate through the tree
- const url = useRef("");
- const [secretUrl, setSecretUrl] = useState("");
- const [secretCode, setSecretCode] = useState("");
- // Standard DFS search, in order
- const searchTree = useCallback((node, currentDepth) => {
- const children = node.children;
- const nodeType = node.nodeName;
- // quick check to filter out improper no types at depth
- // or if anything is greater than the max depth for our pattern
- if (nodeType !== depthMap[currentDepth] || currentDepth > 4) {
- return;
- }
- if (children.length === 0 && node.getAttribute("value")) {
- url.current += node.getAttribute("value");
- return;
- } else if (children.length === 0) {
- return;
- }
- for (let i = 0; i < children.length; i++) {
- searchTree(children[i], currentDepth + 1);
- }
- }, []);
- const fetchHtml = useCallback(async () => {
- const htmlResponse = await fetch(
- "https://tns4lpgmziiypnxxzel5ss5nyu0nftol.lambda-url.us-east-1.on.aws/challenge"
- );
- const html = await htmlResponse.text();
- // Use standard web api so we don't have to build our own tree
- const docToParse = new DOMParser().parseFromString(html, "text/html");
- const root = docToParse.body;
- searchTree(root, 0);
- setSecretUrl(url.current);
- url.current = "";
- }, [searchTree]);
- const fetchSecretCode = useCallback(async () => {
- if (!secretUrl) {
- return;
- }
- const secretCode = await fetch(secretUrl).then((result) => result.text());
- setSecretCode(secretCode);
- }, [secretUrl]);
- useEffect(() => {
- fetchHtml();
- }, [fetchHtml]);
- useEffect(() => {
- fetchSecretCode();
- }, [fetchSecretCode]);
- return (
- <div className="App">
- <h1>Capture The Flag</h1>
- <div className="letterContainer">
- {secretCode ? (
- secretCode.split("").map((letter, index) => (
- <TypewriterLetter key={letter} delay={index}>
- {letter}
- </TypewriterLetter>
- ))
- ) : (
- <p>Loading...</p>
- )}
- </div>
- </div>
- );
- }
- import React, { useState, useEffect, useRef, useCallback } from "react";
- import "./styles.css";
- const InfiniteScroll = () => {
- const [items, setItems] = useState(Array.from({ length: 20 }));
- const [hasMore, setHasMore] = useState(true);
- const loaderRef = useRef(null);
- // Mock function to simulate data fetching
- const fetchMoreItems = () => {
- setTimeout(() => {
- setItems((prevItems) => [
- ...prevItems,
- ...Array.from({ length: 20 }) // Add 20 more items
- ]);
- }, 1000);
- };
- // Intersection Observer to trigger loading more items
- const handleObserver = useCallback((entries) => {
- const target = entries[0];
- if (target.isIntersecting && hasMore) {
- fetchMoreItems();
- }
- }, [hasMore]);
- useEffect(() => {
- const option = {
- root: null,
- rootMargin: "20px",
- threshold: 0.5
- };
- const observer = new IntersectionObserver(handleObserver, option);
- if (loaderRef.current) observer.observe(loaderRef.current);
- return () => observer.disconnect();
- }, [handleObserver]);
- return (
- <div className="infinite-scroll-container">
- <h1>Infinite Scroll Component</h1>
- <ul className="item-list">
- {items.map((_, index) => (
- <li key={index} className="item">
- Item {index + 1}
- </li>
- ))}
- </ul>
- <div ref={loaderRef} className="loading">
- {hasMore ? "Loading more items..." : "No more items to load"}
- </div>
- </div>
- );
- };
- export default InfiniteScroll;
- import React, { useState } from "react";
- // Sample Directory Structure (No 'type' field)
- const directoryData = {
- name: "root",
- children: [
- {
- name: "Documents",
- children: [
- { name: "Resume.pdf" },
- { name: "CoverLetter.docx" }
- ]
- },
- {
- name: "Pictures",
- children: [{ name: "Vacation.jpg" }]
- },
- { name: "notes.txt" }
- ]
- };
- // Recursive Component to Render Directory
- const Directory = ({ data }) => {
- const [expanded, setExpanded] = useState(false);
- // Check if this is a folder (has children)
- const isFolder = Object.hasOwn(data, 'children');
- // Toggle folder expansion
- const handleToggle = () => {
- if (isFolder) {
- setExpanded(!expanded);
- }
- };
- return (
- <div style={{ marginLeft: "20px" }}>
- <div
- onClick={handleToggle}
- style={{ cursor: isFolder ? "pointer" : "default" }}
- >
- {isFolder ? (expanded ? "\u{1F4C2}" : "\u{1F4C1}") : "\u{1F4C4}"} {data.name}
- </div>
- {expanded && isFolder && (
- <div style={{ marginLeft: "20px" }}>
- {data.children.map((child, index) => (
- <Directory key={index} data={child} />
- ))}
- </div>
- )}
- </div>
- );
- };
- // Main App Component
- const App = () => {
- return (
- <div>
- <h2>File Explorer</h2>
- <Directory data={directoryData} />
- </div>
- );
- };
- export default App;
- import React, { useState } from "react";
- // Sample Directory Structure
- const directoryData = {
- name: "root",
- children: [
- {
- name: "Documents",
- children: [
- { name: "Resume.pdf" },
- { name: "CoverLetter.docx" }
- ]
- },
- {
- name: "Pictures",
- children: [{ name: "Vacation.jpg" }]
- },
- { name: "notes.txt" }
- ]
- };
- // Recursive Component to Render Directory
- const Directory = ({ data, isLast = false, level = 0, hasSiblingsAbove = false }) => {
- const [expanded, setExpanded] = useState(false);
- // Check if this is a folder (has children)
- const isFolder = Object.hasOwn(data, 'children');
- // Toggle folder expansion
- const handleToggle = () => {
- if (isFolder) {
- setExpanded(!expanded);
- }
- };
- return (
- <div style={{ position: "relative", marginLeft: level > 0 ? "20px" : "0px" }}>
- {/* Vertical Line (connects this item to parent, but stops at the last child) */}
- {level > 0 && hasSiblingsAbove && (
- <div
- style={{
- position: "absolute",
- left: "-10px",
- top: "0",
- bottom: "0",
- width: "2px",
- backgroundColor: "gray"
- }}
- ></div>
- )}
- {/* Horizontal Connector (connects parent to its children) */}
- {level > 0 && (
- <div
- style={{
- position: "absolute",
- left: "-10px",
- top: "12px",
- width: "10px",
- height: "2px",
- backgroundColor: "gray"
- }}
- ></div>
- )}
- {/* Directory/File Name */}
- <div className="directory-item" onClick={handleToggle} style={{ cursor: isFolder ? "pointer" : "default", display: "flex", alignItems: "center" }}>
- {isFolder ? (expanded ? "\u{1F4C2}" : "\u{1F4C1}") : "\u{1F4C4}"} {data.name}
- </div>
- {/* Render Children */}
- {expanded && isFolder && (
- <div style={{ marginLeft: "15px", paddingLeft: "10px", position: "relative" }}>
- {data.children.map((child, index) => (
- <Directory
- key={index}
- data={child}
- isLast={index === data.children.length - 1}
- level={level + 1}
- hasSiblingsAbove={true} // Ensure the vertical line appears properly
- />
- ))}
- {/* STOP the vertical line at the last child */}
- {isLast && (
- <div
- style={{
- position: "absolute",
- left: "-10px",
- top: "0",
- bottom: "12px", // Stops the line exactly at the bottom of the last child
- width: "2px",
- backgroundColor: "gray"
- }}
- ></div>
- )}
- </div>
- )}
- </div>
- );
- };
- // Main App Component
- const App = () => {
- return (
- <div style={{ padding: "20px", fontFamily: "Arial, sans-serif" }}>
- <h2>{`${"\u{1F4C1}"} File Explorer`}</h2>
- <Directory data={directoryData} />
- </div>
- );
- };
- export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement