htamayo
htamayo

Reputation: 353

Onchange event never triggered using select control in JSX

I'm working with React trying to trigger the onChange event using a Select control in a functional component. The problem is when I select any available option, the onChange listener method is never triggered, this is my code:

import React, { useState } from 'react';
import './ExpensesFilter.css';

const ExpensesFilter = (props) => {
  const [year, setYear] = useState('');

  const yearChangeHandler = (event) => {
    /* setYear actualiza, por medio de useState, 
    a year de manera asincrona, useState es un hooks
     */
    setYear(event);
    console.log("the user is filtering by year");
    console.log("year selected: "+year);
  };

    return (
        <div className='expenses-filter'>
          <div className='expenses-filter__control'>
            <label>Filter by year</label>
            <select onChange={yearChangeHandler}>
              <option value='2022'>2022</option>
              <option value='2021'>2021</option>
              <option value='2020'>2020</option>
              <option value='2019'>2019</option>
            </select>
          </div>
        </div>
      );
}

export default ExpensesFilter;

This component is implemented like this:

import React, { useState } from 'react';
import './Expenses.css';
import ExpenseItemV3 from './ExpenseItemV3';
import Card from '../UI/Card';
import ExpenseFilter from './NewExpense/ExpensesFilter';

const Expenses = (props) => {

    return (
        <div>
            <Card className="expenses">
                <div>
                    <ExpenseFilter />
                    <ExpenseItemV3
                        title={props.records[0].title}
                        amount={props.records[0].amount}
                        date={props.records[0].date}>
                    </ExpenseItemV3>
                </div>
                ...

So far I'm out of ideas, your comments will be highly appreciated, thanks a lot

Upvotes: 0

Views: 182

Answers (2)

IAmRC1
IAmRC1

Reputation: 121

Just add the value={year} in the select tag and in the onChange method, set year to event.target.value. Also, the log statement of year should be outside the onChange handler. Works for me.

Upvotes: 0

Marian Serafimov
Marian Serafimov

Reputation: 77

To set the value of the selected option you will have to reach the event target value and set value to the select tag like this:

setYear(event.target.value);
<select value={year} onChange={yearChangeHandler}>

Upvotes: 1

Related Questions