+1 vote
177 views
by (98.9k points)
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.

1 Answer

0 votes
by (98.9k points)
 
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')
);

 

 

 

Related questions

0 votes
0 answers 37 views

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

559 users

...