0

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

2 Answers 2

1

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}>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the hint @Marian, however, still can't output both console.log lines after setYear, what am I missing?
0

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.

1 Comment

got it, I'll try to chance the place of the console.log lines

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.