React Interview Coding Question

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

Create a component that fetches and displays data from an API.

fetching the API


fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((data) => setData(data));
}, []);

return (
<div>
<h1>Posts</h1>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}

export default DataFetching;

Build a form component that captures user input and displays it.

function UserForm() {
const [name, setName] = useState('');
const [submittedName, setSubmittedName] = useState('');

const handleSubmit = (e) => {


e.preventDefault();
setSubmittedName(name);
};

return (
<div>
<h2>Hello, {submittedName || 'Guest'}!</h2>
<form onSubmit={handleSubmit}>
<label>
Enter your name:
<input type="text" value={name} onChange={(e) => setName(e.target.value)}
/>
<

Create a toggle switch component that changes its state when clicked.

'
import React, { useState } from 'react';

function ToggleSwitch() {
const [isOn, setIsOn] = useState(false);

const toggle = () => setIsOn(!isOn);

return (
<div>
<p>Switch is {isOn ? 'On' : 'Off'}</p>
<button onClick={toggle}>Toggle</button>
</div>
);
}

export default ToggleSwitch;

Implement a simple stopwatch component in React.


import React, { useState, useEffect } from 'react';

function Stopwatch() {
const [time, setTime] = useState(0);
const [isRunning, setIsRunning] = useState(false);

useEffect(() => {
let interval;
if (isRunning) {
interval = setInterval(() => {
setTime((prevTime) => prevTime + 1);
}, 1000);
}
return () => clearInterval(interval);
}, [isRunning]);

const startStop = () => {


setIsRunning(!isRunning);
};

const reset = () => {


setTime(0);

Build a simple image gallery component that displays a list of images.


import React from 'react';

const imageUrls = [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg',
];

function ImageGallery() {
return (
<div>
<h1>Image Gallery</h1>
<ul>
{imageUrls.map((url, index) => (
<li key={index}>
<img src={url} alt={`Image ${index}`} />
</li>
))}
</ul>
</div>
);
}

export default ImageGallery;

You might also like