0% found this document useful (0 votes)
201 views19 pages

React CoderByte Quetions

Uploaded by

helindevani111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
201 views19 pages

React CoderByte Quetions

Uploaded by

helindevani111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

React Button Toggle

--------------------------------------------------------------
import React, { useState } from "react"
import { createRoot } from "react-dom/client"

const Toggle = () => {


const [toggle, setToggle] = useState(false)

const handleClick = () => {


setToggle(!toggle)
}

return (
<button type="button" onClick={handleClick}>
{toggle ? "ON" : "OFF"}
</button>
)
}

const root = createRoot([Link]("root"))


[Link](<Toggle />)
//////////////////////////////////////////////////////////////
React Color Dropdown
--------------------------------------------------------------
import React, { useState } from "react"
import { createRoot } from "react-dom/client"

function ColorSelector() {
const colors = { red: "Red", blue: "Blue", green: "Green" }
const [color, setColor] = useState([Link])
const onChange = e => setColor([Link])
return (
<>
<select onChange={onChange} value={color}>
<option value={[Link]}>{[Link]}</option>
<option value={[Link]}>{[Link]}</option>
<option value={[Link]}>{[Link]}</option>
</select>
{color && <p>{`You have selected: ${color}`}</p>}
</>
)
}

const root = createRoot([Link]("root"))


[Link](<ColorSelector />)
//////////////////////////////////////////////////////////////
React Live Paragraph
---------------------------------------------------------------
import React, { useState } from "react"
import { createRoot } from "react-dom/client"
function LiveText() {
const [text, setText] = useState("")

const onChange = ({ target: { value } }) => {


setText(value)
}
return (
<>
<input type="text" onChange={onChange} value={text} />
<p>{text}</p>
</>
)
}

const root = createRoot([Link]("root"))


[Link](<LiveText />)
//////////////////////////////////////////////////////////////////
React Quiz Builder
-------------------------------------------------------------------
import React, { useState, useMemo } from "react"
import { createRoot } from "react-dom/client"

const style = {
container: {
padding: "20px",
border: "1px solid #E0E0E0",
borderRadius: "15px",
width: "max-content",
marginBottom: "40px",
},
question: {
fontWeight: "bold",
marginBottom: "10px",
},
options: {
marginBottom: "5px",
},
button: {
marginTop: "10px",
padding: "10px 15px",
border: "none",
backgroundColor: "#007BFF",
color: "#FFF",
fontSize: "14px",
borderRadius: "5px",
cursor: "pointer",
},
feedback: {
marginTop: "10px",
fontSize: "14px",
},
}

const QuizOption = ({ option, index, answer, setAnswer }) => {


const onChange = ({ target: { value } }) => setAnswer(value)
return (
<>
<input
type="radio"
onChange={onChange}
checked={option === answer}
name="answers"
value={option}
id={`option${index}`}
/>
<label htmlFor={option}>{option}</label>
</>
)
}

function QuizApp() {
// do not modify the questions or answers below
const questions = useMemo(
() => [
{
question: "What is the capital of France?",
options: ["London", "Paris", "Berlin", "Madrid"],
correct: "Paris",
},
{
question: "What is the capital of Germany?",
options: ["Berlin", "Munich", "Frankfurt", "Hamburg"],
correct: "Berlin",
},
],
[]
)

const questionsTotal = useMemo(() => [Link], [questions])

const [questionsIndex, setQuestionsIndex] = useState(0)


const [score, setScore] = useState(0)
const [feedback, setFeedback] = useState(null)
const [answer, setAnswer] = useState(null)
const [completedQuiz, setCompletedQuiz] = useState(false)

const submit = () => {


if (answer === questions[questionsIndex].correct) {
setScore(score + 1)
setFeedback("Correct!")
} else {
setFeedback("Incorrect!")
}

if (questionsIndex === questionsTotal - 1) {


setCompletedQuiz(true)
} else {
setQuestionsIndex(questionsIndex + 1)
setAnswer(null)
}
}

return (
<div style={[Link]}>
<div id="question" style={[Link]}>
{`${questions[questionsIndex].question}`}
</div>
<div style={[Link]}>
{questions[questionsIndex].[Link]((option, index) => (
<QuizOption
key={`option-${index}`}
option={option}
index={index}
answer={answer}
setAnswer={setAnswer}
/>
))}
</div>
<button
disabled={completedQuiz}
style={[Link]}
id="submitBtn"
onClick={submit}
>
Submit
</button>
<div id="feedback" style={[Link]}>
{questionsIndex !== 0 && !completedQuiz && `${feedback}`}
</div>
<div id="score" style={[Link]}>
{completedQuiz &&
`Quiz complete! You scored ${score} out of
${[Link]}!`}
</div>
</div>
)
}

const root = createRoot([Link]("root"))


[Link](<QuizApp />)
////////////////////////////////////////////////////////////////////
React Weather Dashboard
----------------------------------------------------------------------
import React, { useState } from "react"
import { createRoot } from "react-dom/client"

const style = {
marginTop: {
marginTop: "10px",
},
marginRight: {
marginRight: "10px",
},
}

const WeatherDashboard = () => {


// instead of requesting data from an API, use this mock data
const mockWeatherData = {
"New York": {
temperature: "22°C",
humidity: "56%",
windSpeed: "15 km/h",
},
"Los Angeles": {
temperature: "27°C",
humidity: "45%",
windSpeed: "10 km/h",
},
London: {
temperature: "15°C",
humidity: "70%",
windSpeed: "20 km/h",
},
}

const defaultWeather = {
temperature: "",
humidity: "",
windSpeed: "",
}

const [city, setCity] = useState("")


const [cache, setCache] = useState({})
const [notFound, setNotFound] = useState(false)
const [previousSearches, setPreviousSearches] = useState([])
const [weather, setWeather] = useState(defaultWeather)

const mockFetchWeatherData = city => {


return new Promise((resolve, reject) => {
setTimeout(() => {
if (mockWeatherData[city]) {
resolve(mockWeatherData[city])
} else {
reject(new Error("City not found."))
setNotFound(true)
setWeather(defaultWeather)
}
}, 500)
})
}

const search = async city => {


setNotFound(false)

if (!city || city === "") {


setWeather(defaultWeather)
setNotFound(true)
return
}

if (cache[city]) {
setWeather(cache[city])
return
}

try {
const data = await mockFetchWeatherData(city)
setCache({ ...cache, [city]: data })
setWeather(data)
setPreviousSearches([...previousSearches, city])
} catch {
throw new Error("Could not fetch weather data.")
}
}

return (
<div>
<input
type="text"
id="citySearch"
placeholder="Search for a city..."
value={city}
onChange={e => setCity([Link])}
/>
<button id="searchButton" onClick={() => search(city)}>
Search
</button>
<div id="weatherData" style={[Link]}>
<div>Temperature: {[Link]}</div>
<div>Humidity: {[Link]}</div>
<div>Wind Speed: {[Link]}</div>
{notFound && <div style={[Link]}>City not found.</div>}
</div>
<div id="previousSearches" style={[Link]}>
{[Link] > 0 &&
[Link]((previousSearch, index) => (
<button
key={index}
onClick={() => {
setCity(previousSearch)
search(previousSearch)
}}
style={[Link]}
>
{previousSearch}
</button>
))}
</div>
</div>
)
}

const root = createRoot([Link]("root"))


[Link](<WeatherDashboard />)
////////////////////////////////////////////////////////////////////////
React Letter Tiles
---------------------------------------------------------------------
import React, { useState, useCallback, useMemo } from "react"
import { createRoot } from "react-dom/client"

const style = {
letterContainer: {
overflow: "auto",
marginBottom: "10px",
display: "flex",
flexWrap: "wrap",
justifyContent: "center",
alignItems: "center",
},
letter: {
float: "left",
padding: "10px 10px",
background: "#c9e4ed",
borderRadius: "5px",
marginRight: "5px",
marginTop: "5px",
cursor: "pointer",
},
outputString: {
marginTop: "20px",
textAlign: "center",
},
}

const Tile = ({ letter, outputArray, setOutputArray, tally, setTally }) => {


const onClick = useCallback(() => {
if (!tally[letter]) {
setTally({ ...tally, [letter]: 1 })
setOutputArray([...outputArray, letter])
} else if (tally[letter] && tally[letter] === 2) {
setTally({ ...tally, [letter]: 0 })
const slicedArray = [Link](0, [Link] - 2)
setOutputArray([...slicedArray, "_"])
} else {
setTally({ ...tally, [letter]: tally[letter] + 1 })
setOutputArray([...outputArray, letter])
}
}, [letter, outputArray, setOutputArray, tally, setTally])

return (
<button type="button" onClick={onClick} style={[Link]}>
{letter}
</button>
)
}

const Application = () => {


const [outputArray, setOutputArray] = useState([])
const [tally, setTally] = useState({})
const alphabetArray = useMemo(() => {
const arr = []
for (let i = 65; i <= 90; i++) {
const char = [Link](i)
[Link](char)
}
return arr
}, [])
return (
<section>
<aside style={[Link]} id="letterContainer">
{[Link]((letter, index) => (
<Tile
tally={tally}
setTally={setTally}
letter={letter}
key={index}
outputArray={outputArray}
setOutputArray={setOutputArray}
/>
))}
</aside>
<div style={[Link]} id="outputString">
{[Link]("")}
</div>
</section>
)
}

const root = createRoot([Link]("root"))


[Link](<Application />)
//////////////////////////////////////////////////////////////////
React TypeScript Button Toggle
----------------------------------------------------------------------
import React, { useState, ReactNode } from "react"
import { createRoot } from "react-dom/client"

const Toggle: ReactNode = () => {


const [toggle, setToggle] = useState<boolean>(true)

const onClick = (): void => {


setToggle(!toggle)
}

return <button onClick={onClick}>{toggle ? "ON" : "OFF"}</button>


}

const root = createRoot([Link]("root"))


[Link](<Toggle />)
////////////////////////////////////////////////////////////////////
React Context API
--------------------------------------------------------------------------
import React, { useState, createContext, useContext } from "react"
import { createRoot } from "react-dom/client"

const languages = ["JavaScript", "Python"]


const LanguageContext = createContext({
languages,
language: languages[0],
setLanguage: () => {},
})

const MainSection = () => {


const { languages, language, setLanguage } = useContext(LanguageContext)
const currentIndex = [Link](language)
const toggleLanguage = () =>
currentIndex === [Link] - 1
? setLanguage(languages[0])
: setLanguage(languages[currentIndex + 1])
return (
<div>
<p id="favoriteLanguage">{`Favorite programming language:
${language}`}</p>
<button id="changeFavorite" onClick={toggleLanguage}>
Toggle language
</button>
</div>
)
}

const App = () => {


const [language, setLanguage] = useState(languages[0])
return (
<[Link] value={{ languages, language, setLanguage }}>
<MainSection />
</[Link]>
)
}

const root = createRoot([Link]("root"))


[Link](<App />)
///////////////////////////////////////////////////////////////////////
React Native Simple Counter
---------------------------------------------------------------------------
import React, { useState } from "react"
import { Text, View, StyleSheet } from "react-native"

const SimpleCounter = () => {


const [count, setCount] = useState(0)

const increment = () => setCount(count + 1)

return (
<View style={[Link]}>
<Text style={[Link]}>
button count: <span id="actualCount">{count}</span>
</Text>
<button id="mainButton" onClick={increment}>
Increase
</button>
</View>
)
}

const styles = [Link]({


container: {
flex: 1,
justifyContent: "center",
marginHorizontal: 10,
},
counter: {
textAlign: "center",
marginVertical: 20,
},
})

export default SimpleCounter


/////////////////////////////////////////////////////////////////////////
React Tic Tac Toe
-------------------------------------------------------------------------
import React, { useState } from "react"
import { createRoot } from "react-dom/client"

const rowStyle = {
display: "flex",
}

const squareStyle = {
width: "60px",
height: "60px",
backgroundColor: "#ddd",
margin: "4px",
display: "flex",
justifyContent: "center",
alignItems: "center",
fontSize: "20px",
color: "white",
}

const disabledSquareStyle = {
...squareStyle,
cursor: "not-allowed",
}

const boardStyle = {
backgroundColor: "#eee",
width: "208px",
alignItems: "center",
justifyContent: "center",
display: "flex",
flexDirection: "column",
border: "3px #eee solid",
}

const containerStyle = {
display: "flex",
alignItems: "center",
flexDirection: "column",
}
const instructionsStyle = {
marginTop: "5px",
marginBottom: "5px",
fontWeight: "bold",
fontSize: "16px",
}

const buttonStyle = {
marginTop: "15px",
marginBottom: "16px",
width: "80px",
height: "40px",
backgroundColor: "#8acaca",
color: "white",
fontSize: "16px",
}

const Square = ({ value, onClick, winner }) => {


return (
<button
className="square"
onClick={() => onClick(value)}
style={
value !== null || winner !== "None"
? disabledSquareStyle
: squareStyle
}
disabled={value !== null || winner !== "None"}
>
{value}
</button>
)
}

const Board = () => {


const [player, setPlayer] = useState("X")
const [winner, setWinner] = useState("None")
const [board, setBoard] = useState(() => Array(9).fill(null))

const matches = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
]
const checkWinner = newBoard => {
for (let i = 0; i < [Link]; i++) {
const [a, b, c] = matches[i]
if (
newBoard[a] === player &&
newBoard[b] === player &&
newBoard[c] === player
) {
return true
}
}
return false
}

const onClick = index => {


const newBoard = [...board]
newBoard[index] = player
setBoard(newBoard)

if (checkWinner(newBoard)) {
setWinner(player)
} else {
setPlayer(player === "X" ? "O" : "X")
}
}

const onReset = () => {


setBoard(Array(9).fill(null))
setPlayer("X")
setWinner("None")
}

return (
<div style={containerStyle} className="gameBoard">
<div id="statusArea" className="status" style={instructionsStyle}>
Next player: <span>{player === "X" ? "O" : "X"}</span>
</div>
<div id="winnerArea" className="winner" style={instructionsStyle}>
Winner: <span>{winner !== "None" && winner}</span>
</div>
<button style={buttonStyle} onClick={onReset}>
Reset
</button>
<div style={boardStyle}>
<div className="board-row" style={rowStyle}>
<Square
value={board[0]}
onClick={() => onClick(0)}
winner={winner}
/>
<Square
value={board[1]}
onClick={() => onClick(1)}
winner={winner}
/>
<Square
value={board[2]}
onClick={() => onClick(2)}
winner={winner}
/>
</div>
<div className="board-row" style={rowStyle}>
<Square
value={board[3]}
onClick={() => onClick(3)}
winner={winner}
/>
<Square
value={board[4]}
onClick={() => onClick(4)}
winner={winner}
/>
<Square
value={board[5]}
onClick={() => onClick(5)}
winner={winner}
/>
</div>
<div className="board-row" style={rowStyle}>
<Square
value={board[6]}
onClick={() => onClick(6)}
winner={winner}
/>
<Square
value={board[7]}
onClick={() => onClick(7)}
winner={winner}
/>
<Square
value={board[8]}
onClick={() => onClick(8)}
winner={winner}
/>
</div>
</div>
</div>
)
}
const Game = () => {
return (
<div className="game">
<div className="game-board">
<Board />
</div>
</div>
)
}

const root = createRoot([Link]("root"))


[Link](<Game />)
/////////////////////////////////////////////////////////////////////////
React Simple Counter
-----------------------------------------------------------------------------
import React, { useState } from "react"
import { createRoot } from "react-dom/client"

const Counter = () => {


const [count, setCount] = useState(0)

const increment = () => {


setCount(prevCount => prevCount + 1)
}

return (
<div id="mainArea">
<p>
{`Button Count: `}
<span>{count}</span>
</p>
<button onClick={increment} id="mainButton">
Increase
</button>
</div>
)
}

const root = createRoot([Link]("root"))


[Link](<Counter />)
///////////////////////////////////////////////////////////////////////////////
React Phone Book
------------------------------------------------------------------------------
import React, { useState, useReducer, useCallback } from "react"
import { createRoot } from "react-dom/client"

const style = {
table: {
borderCollapse: "collapse",
},
tableCell: {
border: "1px solid gray",
margin: 0,
padding: "5px 10px",
width: "max-content",
minWidth: "150px",
},
form: {
container: {
padding: "20px",
border: "1px solid #F0F8FF",
borderRadius: "15px",
width: "max-content",
marginBottom: "40px",
},
inputs: {
marginBottom: "5px",
},
submitBtn: {
marginTop: "10px",
padding: "10px 15px",
border: "none",
backgroundColor: "lightseagreen",
fontSize: "14px",
borderRadius: "5px",
},
},
}

function PhoneBookForm({ entries, setEntries }) {


const initialFormState = {
userFirstname: "Coder",
userLastname: "Byte",
userPhone: "8885559999",
}

const formReducer = (state, { type, payload }) => {


switch (type) {
case "RESET":
return { userFirstname: "", userLastname: "", userPhone: "" }
default:
return { ...state, [type]: payload }
}
}

const [formState, dispatch] = useReducer(formReducer, initialFormState)

const onChange = ({ target: { name, value } }) =>


dispatch({ type: name, payload: value })
const addEntryToPhoneBook = useCallback(() => {
const { userFirstname, userLastname, userPhone } = formState
const newEntries = [
...entries,
{ userFirstname, userLastname, userPhone },
]
const newSortedEntries = [Link]((a, b) => {
const userLastnameA = [Link]()
const userLastnameB = [Link]()
return userLastnameA < userLastnameB
? -1
: userLastnameA > userLastnameB
? 1
: 0
})
setEntries(newSortedEntries)
}, [formState])

return (
<form
onSubmit={e => {
[Link]()
addEntryToPhoneBook(formState)
dispatch({ type: "RESET" })
}}
style={[Link]}
>
<label>First name:</label>
<br />
<input
style={[Link]}
className="userFirstname"
name="userFirstname"
type="text"
onChange={onChange}
value={[Link]}
/>
<br />
<label>Last name:</label>
<br />
<input
style={[Link]}
className="userLastname"
name="userLastname"
type="text"
onChange={onChange}
value={[Link]}
/>
<br />
<label>Phone:</label>
<br />
<input
style={[Link]}
className="userPhone"
name="userPhone"
type="text"
onChange={onChange}
value={[Link]}
/>
<br />
<input
style={[Link]}
className="submitButton"
type="submit"
value="Add User"
/>
</form>
)
}

function InformationTable({ entries }) {


return (
<table style={[Link]} className="informationTable">
<thead>
<tr key={`row-0`}>
<th style={[Link]}>First name</th>
<th style={[Link]}>Last name</th>
<th style={[Link]}>Phone</th>
</tr>
{[Link](
({ userFirstname, userLastname, userPhone }, index) => (
<tr key={`row-${index + 1}`}>
<td style={[Link]}>{userFirstname}</td>
<td style={[Link]}>{userLastname}</td>
<td style={[Link]}>{userPhone}</td>
</tr>
)
)}
</thead>
</table>
)
}

function Application() {
const [entries, setEntries] = useState([])
return (
<section>
<PhoneBookForm entries={entries} setEntries={setEntries} />
<InformationTable entries={entries} />
</section>
)
}

const root = createRoot([Link]("root"))


[Link](<Application />)
///////////////////////////////////////////////////////////////////////////////
React List
-------------------------------------------------------------------------------
import React from "react"
import { createRoot } from "react-dom/client"

const data = [
{ name: "Daniel", age: 25 },
{ name: "John", age: 24 },
{ name: "Jen", age: 31 },
]

const DataItem = ({ name, age }) => (


<li>
<span>{`${name} `}</span>
<span>{age}</span>
</li>
)

const DataList = ({ data }) => (


<div>
<h2>Data List</h2>
<ul>
{[Link]((dataItem, index) => (
<DataItem
name={[Link]}
age={[Link]}
key={`data-item-${index}`}
/>
))}
</ul>
</div>
)

const root = createRoot([Link]("root"))


[Link](<DataList data={data} />)
///////////////////////////////////////////////////////////////////////////////

You might also like