OnChange event using React JS for drop down

OnChange event using React JS for drop down

React JS is a popular JavaScript library used for building user interfaces. One common requirement when working with forms is to perform an action when the value of a drop-down menu changes. In React, this can be achieved using the onChange event.

Let’s explore how to handle the onChange event for a drop-down menu in React JS.

1. Using a Class Component

If you are using a class component in React, you can define a method that will be called when the value of the drop-down menu changes. Here’s an example:


import React, { Component } from 'react';

class DropDown extends Component {
  handleChange(event) {
    const selectedValue = event.target.value;
    // Perform any action with the selected value
    console.log(selectedValue);
  }

  render() {
    return (
      
    );
  }
}

export default DropDown;

In this example, we have defined a DropDown component that renders a drop-down menu. The onChange event is attached to the select element, and it calls the handleChange method whenever the value changes. The selected value can be accessed using event.target.value.

2. Using a Functional Component with Hooks

If you are using functional components with React Hooks, you can achieve the same result using the useState hook. Here’s an example:


import React, { useState } from 'react';

const DropDown = () => {
  const [selectedValue, setSelectedValue] = useState('');

  const handleChange = (event) => {
    const value = event.target.value;
    setSelectedValue(value);
    // Perform any action with the selected value
    console.log(value);
  };

  return (
    
  );
};

export default DropDown;

In this example, we have defined a functional component called DropDown. We use the useState hook to create a state variable selectedValue and a function setSelectedValue to update its value. The handleChange function is called whenever the value changes, and it updates the selectedValue state. The selected value can be accessed directly using selectedValue.

These are two common approaches to handle the onChange event for a drop-down menu in React JS. Depending on your project’s requirements and coding style, you can choose the one that suits you best.

That’s it! You now know how to handle the onChange event using React JS for a drop-down menu. Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *