menu search
brightness_auto
more_vert
Explain the concept of Hooks in React. Write a code making use of React Hooks that displays four buttons namely, “Red”, “Blue”, “Green”, “Yellow”. On clicking any of these buttons, the code displays the message that you have selected that particular color.
thumb_up_off_alt 1 like thumb_down_off_alt 0 dislike

1 Answer

more_vert
 
verified
Best answer

React Hooks are functions that allow functional components to have state, lifecycle methods, and other React features. They were introduced in React 16.8 to provide a way to use state and other React features in functional components instead of class components.

Rules for Using Hooks:

  1. Only use Hooks at the top level of a functional component or a custom hook.
  2. Only call Hooks from functional components or custom hooks; do not call them in regular JavaScript functions.
  3. Hooks should be called in the same order every time the component renders.
  4. Hooks cannot be called conditionally; they should be called in the same order every render.

 

Code : 

import React, { useState } from 'react';

const ColorSelector = () => {
  const [selectedColor, setSelectedColor] = useState(null);

  const handleColorClick = (color) => {
    setSelectedColor(color);
  };

  return (
    <div>
      <h2>Selected Color: {selectedColor}</h2>
      <button onClick={() => handleColorClick('Red')}>Red</button>
      <button onClick={() => handleColorClick('Blue')}>Blue</button>
      <button onClick={() => handleColorClick('Green')}>Green</button>
      <button onClick={() => handleColorClick('Yellow')}>Yellow</button>
    </div>
  );
};

export default ColorSelector;

 

 

Now Import ColorSelector in   index.js

import React from 'react';
import ReactDOM from 'react-dom';
import ColorSelector from './ColorSelector';

ReactDOM.render(
  <React.StrictMode>
    <ColorSelector />
  </React.StrictMode>,
  document.getElementById('root')
);

 

 

 

thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike

Related questions

thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 1 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
0 answers
thumb_up_off_alt 1 like thumb_down_off_alt 0 dislike
1 answer

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

648 users

...