State and Event listeners in React

In React, the useState hook allows a component to have a state, which is an object that holds some data that can change over time. The state can be updated by calling the setState function, which is returned by the useState hook. The useState hook takes an initial value as an argument and returns an array with two elements: the current state and the setState function.

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "name"
  // set its initial value to an empty string
  const [name, setName] = useState('');

  return (
    <div>
      <label>Enter your name:</label>
      <input type="text" value={name} onChange={event => setName(event.target.value)} />
      <p>Hello, {name}!</p>
    </div>
  );
}

//Output-
<p>Hello, {name}!</p>

Here the component has an input field that allows the user to enter their name.

The value of the input field is set to the current state of the name variable, and the onChange event is used to call the setName function, passing in the current value of the input field.

This way when user types something in input field and as soon as user type something, the state is getting updated and the UI with the name value is getting re-rendered.

--> Event Listeners

Here are the list of some common event listeners-

  • onClick: This event is triggered when an element is clicked.

  • onChange: This event is triggered when the value of an input field changes.

  • onSubmit: This event is triggered when a form is submitted.

  • onKeyDown: This event is triggered when a key is pressed down on the keyboard.

  • onMouseEnter: This event is triggered when the mouse pointer enters an element.

  • onMouseLeave: This event is triggered when the mouse pointer leaves an element.

  • onFocus: This event is triggered when an element receives focus.

  • onBlur: This event is triggered when an element loses focus.

  • onLoad: This event is triggered when an element or the entire page has been loaded.

  • onError: This event is triggered when an error occurs while loading an element.

1-Onclick

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>
        Click me
      </button>
    </div>
  );
}

In this example, the component has a state called count which is initialized with a value of 0 using useState(0).

The component also has a button that, when clicked, calls the handleClick function which updates the state and re-render the component by calling setCount(count + 1).

2-Onchange

import React, { useState } from 'react'

function Events() {
    const [inputValue, setInputValue] = useState('');

    function handleChange(event){
        setInputValue(event.target.value)
    }
  return (
    <div>
          <h1>Enter Your Name</h1>
          <input type="text" value={inputValue} onChange={handleChange} />
          <p>You entered: {inputValue}</p>
    </div>
  )
}

export default Events

//Output
//Enter Your Name
//Tia
//You entered: Tia

In this example, the component has a state called inputValue which is initialized with an empty string using useState(''). The component also has an input field that allows the user to enter their name.

The value of the input field is set to the current state of the inputValue variable, and the onChange event is used to call the handleChange function, passing in the current event.

In the handleChange function, the value of the input field is extracted from the event object and passed to the setInputValue function to update the state.

When the input value changes, the component re-renders and the updated value of inputValue is displayed in the component.

3-onFocus & onBlur

import React, { useState } from 'react'

function Events() {
        const [hasFocus, setHasFocus] = useState(false);

        function handleFocus() {
            setHasFocus(true);
        }
        function handleBlur() {
            setHasFocus(false);
        }

        return (
            <div>
                <input type="text" onFocus={handleFocus} onBlur={handleBlur} />
                {hasFocus && <p>The input has focus</p>}
                {!hasFocus && <p>The input has not focus</p>}
            </div>
        )
}

export default Events

In this example, the component has a state called hasFocus which is initialized with a value of false using useState(false). The component also has an input field that allows the user to enter text.

In the handleFocus function, the setHasFocus state is set to true, and in the handleBlur function, the setHasFocus state is set to false.

When the input field receives focus, the component re-renders and the message "The input has focus" is displayed while the input has not the focus "The input has not focus" will be pop out in the component.

4-MouseEnter & MouseLeave

import React, { useState } from 'react'

function Events() {
  const [isHovered, setIsHovered] = useState(false);

  function handleMouseEnter() {
    setIsHovered(true);
  }

  function handleMouseLeave() {
    setIsHovered(false);
  }
  return (
    <div onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
    {isHovered ? "You are hovering over the div" : "Hover over the div"}
  </div>
  );
}

export default Events

When the mouse pointer enters the div element, the component re-renders and the message "You are hovering over the div" is displayed, and when the mouse pointer leaves the div element, the message "Hover over the div" is displayed.