javascriptreactjsdropdownselect-options

reset/clear selected values in select-option on button click in React.js?


I'm working on react and I have several drop-down and text fields where I want to clear/reset selected values from the select options and from the text field when I click the clear button. I've tried some logic, but it doesn't work. can someone help me? I created a function called "handleReset" but it does nothing and doesn't show an error.

Here is my code:

import React, { useState, useEffect } from "react";
import {
  Button,
  Container,
} from "react-bootstrap";
import { CarAction } from "../../Store/Actions/CarAction";
import { useDispatch, useSelector } from "react-redux";

const CarRequests = () => {
  const dispatch = useDispatch();
  const getCarMake = useSelector((state) => state.CarReducer.car);
  const getCarMileage = useSelector((state) => state.CarReducer.mileage);
  const getCarTrim = useSelector((state) => state.CarReducer.trim);

  let [value, setValue] = useState()

  let handleChange = (e) => {
    setValue(e.target.value)
  }

  const handleReset = (e) => {
    setValue(e.target.value = "");
  }

 
  useEffect(() => {
    dispatch(CarAction.CarMake());
    dispatch(CarAction.CarMileage());
    dispatch(CarAction.CarTrim());
  }, [dispatch]);

 
  return (
    <div className="flex-row align-items-center section">
      <h3>
        Filters
        <i className="fa fa-cog icon float-right"></i>
      </h3>
      <Container className="box-shadow p-4">
        <div className="form-row">
          <div className="form-group col-lg-3">
            <label>Make:</label>
            <select className="custom-select" onChange={handleChange}>
            <option value=''>Please select...</option>
              {getCarMake.map((data, key) => <option value={data.value} key={key}>{data.name}</option>)}
            </select>

          </div>

          <div className="form-group col-md-3">
            <label>Model:</label>
            <select className="custom-select">
            <option value=''>Please select...</option>
              <option value="1">Option 1</option>
              <option value="2">Option 2</option>
              <option value="3">Option 3</option>

            </select>
          </div>

          <div className="form-group col-md-3">
            <label>Year:</label>
            <select className="custom-select">
            <option value=''>Please select...</option>
              <option value="1">Option 1</option>
              <option value="2">Option 2</option>
              <option value="3">Option 3</option>
            </select>
          </div>

          <div className="form-group col-md-3">
            <label>Mileage:</label>
            <select className="custom-select" onChange={handleChange}>
            <option value=''>Please select...</option>
              {getCarMileage.map((data, key) => <option value={data.value} key={key}>{data.name}</option>)}

            </select>
          </div>

        </div>

        <div className="form-row">

          <div className="form-group col-md-3">
            <label>Car Trim:</label>
            <select className="custom-select" onChange={handleChange}>
            <option value=''>Please select...</option>
              {getCarTrim.map((data, key) => <option value={data.value} key={key}>{data.name}</option>)}

            </select>
          </div>

          <div className="form-group col-md-3">
            <label>Email:</label>
            <input type="email" placeholder="Email" className="custom-select" />
          </div>

          <div className="form-group col-md-3">
            <label>Phone no:</label>
            <input type="number" placeholder="Phone no" className="custom-select" />
          </div>

        </div>
        <div className="container-buttons">
          <Button className="mr-4" variant="light">
            Search
          </Button>

          <Button variant="dark" onClick={handleReset}>Clear</Button>
        </div>
      </Container>
    </div>
  );
};

export default CarRequests;

Solution

  • The thing you are doing wrong is in handleReset function you are taking the event and you are setting the target value to empty which is ideally wrong. In order to correct it we need to understand how the flow is working, you are using handleChange function in order to set the values to your state. So in order to reset it you need to reset the value of the state only.

    So the code becomes like this:

    const handleReset = () => {
        setValue("");   
    }
    

    Now this will reset the value of your state variable and also use your state variable in your select method which will resolve the problem.

    <select value={value}>
    <option></option>
    .
    .
    </select>
    

    To make dynamic field working:

    function App() {
      const [value, setValue] = useState({});
      const arr = ["hello", "cra"];
      const arr2 = [
        {
          name: "hello",
          id: "1",
        },
        {
          name: "test2",
          id: "2",
        },
      ];
    
      const handleChange = ({ target: { value: val, name } }) => {
        setValue({ ...value, [name]: val });
      };
    
      const resetValue = () => {
        setValue({});
      };
    
      console.log(value);
    
      return (
        <div id="wrapper">
          <select
            name="select1"
            value={value.select1 || ""}
            onChange={handleChange}
          >
            <option value=""></option>
            {arr.map((val) => {
              return <option value={val}>{val}</option>;
            })}
          </select>
          <select
            name="select2"
            value={value.select2 || ""}
            onChange={handleChange}
          >
            <option value=""></option>
            {arr2.map(({ name, id }) => {
              return <option value={id}>{name}</option>;
            })}
          </select>
          <button onClick={resetValue}>Reset</button>
        </div>
      );
    }

    Or else you can initialise the value in your state as well like this

    const [value, setValue] = useState({select1: "" , select2: ""});
    

    which could further be used dynamically in your select tag for name attributes.

    function App() {
      const [value, setValue] = useState({ select1: "", select2: "" });
      const arr = ["hello", "cra"];
      const arr2 = [
        {
          name: "hello",
          id: "1",
        },
        {
          name: "test2",
          id: "2",
        },
      ];
    
      const handleChange = ({ target: { value: val, name } }) => {
        setValue({ ...value, [name]: val });
      };
    
      const resetValue = () => {
        setValue({
          select1: "",
          select2: "",
        });
      };
    
      console.log(value);
    
      return (
        <div id="wrapper">
          <select name="select1" value={value.select1} onChange={handleChange}>
            <option value=""></option>
            {arr.map((val) => {
              return <option value={val}>{val}</option>;
            })}
          </select>
          <select name="select2" value={value.select2} onChange={handleChange}>
            <option value=""></option>
            {arr2.map(({ name, id }) => {
              return <option value={id}>{name}</option>;
            })}
          </select>
          <button onClick={resetValue}>Reset</button>
        </div>
      );
    }