Flat Preloader Icon

Programming Question Of React Js

1. Create a functional component that displays “Hello, World!” on the screen

				
					import React from 'react';

const HelloWorld = () => {
  return <h1>Hello, World!</h1>;
};

export default HelloWorld;

				
			

2. Create a counter component that increments and decrements the count on button clicks

				
					import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() =>
           setCount(count + 1)}>Increment</button>
      <button onClick={() =>
           setCount(count - 1)}>Decrement</button>
    </div>
  );
};

export default Counter;

				
			

3. Create a component that shows “Logged In” if a user is logged in and “Logged Out” if not

				
					import React, { useState } from 'react';

const LoginStatus = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <div>
      {isLoggedIn ? <p>Logged In</p> : <p>Logged Out</p>}
      <button onClick={() => setIsLoggedIn(!isLoggedIn)}>
        Toggle Login Status
      </button>
    </div>
  );
};

export default LoginStatus;

				
			

4. Create a form with a text input and a submit button. Display the input value below the form when submitted

				
					import React, { useState } from 'react';

const FormComponent = () => {
  const [inputValue, setInputValue] = useState('');
  const [submittedValue, setSubmittedValue] =
  useState('');

  const handleSubmit = (event) => {
    event.preventDefault();
    setSubmittedValue(inputValue);
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
        />
        <button type="submit">Submit</button>
      </form>
      {submittedValue && <p>Submitted Value: 
      {submittedValue}</p>}
    </div>
  );
};

export default FormComponent;

				
			

5. Create a component that fetches data from a public API and displays it.

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

const FetchDataComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => response.json())
      .then((data) => setData(data))
      .catch((error) => console.error
      ('Error fetching data:', error));
  }, []);

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

export default FetchDataComponent;

				
			

6. Create a context and a provider to manage a global state

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

const ThemeContext = createContext();

const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};

const ThemedComponent = () => {
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <div style={{ background: theme === 'light' ? '#fff'
    : '#333', color: theme === 'light' ? '#000' :
    '#fff' }}>
      <p>Current Theme: {theme}</p>
      <button onClick={() => setTheme(theme ===
      'light' ? 'dark' : 'light')}>
        Toggle Theme
      </button>
    </div>
  );
};

export { ThemeProvider, ThemedComponent };

				
			

7. Set up a simple routing mechanism in a React application.

				
					import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link }
from 'react-router-dom';

const Home = () => <h1>Home</h1>;
const About = () => <h1>About</h1>;

const App = () => {
  return (
    <Router>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </nav>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </Switch>
    </Router>
  );
};

export default App;

				
			

8. Write a component that accepts a name prop and displays a greeting

				
					const Greeting = ({ name }) => {
    return <h1>Hello, {name}!</h1>;
};

				
			

9. Create a class component that logs a message to the console when it mounts and unmounts.

				
					import React, { Component } from 'react';

class LifecycleDemo extends Component {
    componentDidMount() {
        console.log('Component mounted');
    }

    componentWillUnmount() {
        console.log('Component unmounted');
    }

    render() {
        return <div>Check the console</div>;
    }
}

export default LifecycleDemo;

				
			

10. Create a simple context for managing a theme (light/dark) and a component that consumes the context.

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

const ThemeContext = createContext();

const ThemeProvider = ({ children }) => {
    const [theme, setTheme] = useState('light');

    const toggleTheme = () => {
        setTheme((prevTheme) => 
        (prevTheme === 'light' ? 'dark' : 'light'));
    };

    return (
        <ThemeContext.Provider value=
        {{ theme, toggleTheme }}>
            {children}
        </ThemeContext.Provider>
    );
};

const ThemedComponent = () => {
    const { theme, toggleTheme } = 
    useContext(ThemeContext);

    return (
        <div style={{ background: theme === 'light' ? 
        
'#fff' : '#333', color: theme === 'light' ?
'#000' : '#fff' }}>
            <p>Current theme: {theme}</p>
            <button onClick={toggleTheme}>
                Toggle Theme</button>
        </div>
    );
};

const App = () => (
    <ThemeProvider>
        <ThemedComponent />
    </ThemeProvider>
);

export default App;

				
			

11. Create a custom hook that logs the current window size and updates it on resize

				
					import { useState, useEffect } from 'react';

const useWindowSize = () => {
    const [size, setSize] = useState({
        width: window.innerWidth,
        height: window.innerHeight,
    });

    useEffect(() => {
        const handleResize = () => {
            setSize({
                width: window.innerWidth,
                height: window.innerHeight,
            });
        };

        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener
        ('resize', handleResize);
    }, []);

    return size;
};

const WindowSizeComponent = () => {
    const { width, height } = useWindowSize();

    return (
        <div>
            <p>Width: {width}</p>
            <p>Height: {height}</p>
        </div>
    );
};

export default WindowSizeComponent;

				
			

12. Create a parent component that re-renders frequently and a child component that only re-renders when its props change.

				
					import React, { useState } from 'react';

const ChildComponent = React.memo(({ count }) => {
    console.log('ChildComponent rendered');
    return <p>Child count: {count}</p>;
});

const ParentComponent = () => {
    const [parentCount, setParentCount] = useState(0);
    const [childCount, setChildCount] = useState(0);

    return (
        <div>
            <p>Parent count: {parentCount}</p>
            <button onClick={() =>
 setParentCount(parentCount + 1)}>Increment Parent
 </button>
            <button onClick={() =>
 setChildCount(childCount + 1)}>Increment Child</button>
            <ChildComponent count={childCount} />
        </div>
    );
};

export default ParentComponent;

				
			

13. Implement code splitting for a component using React.lazy and Suspense.

				
					import React, { Suspense, lazy } from 'react';

const LazyComponent = lazy(() => import
('./LazyComponent'));

const App = () => (
    <div>
        <Suspense fallback={<div>Loading...</div>}>
            <LazyComponent />
        </Suspense>
    </div>
);

export default App;