John
John

Reputation: 11901

How to clear <Input type="select"> selected value in Reactstrap?

I have a <select> object in Reactstrap, created by means of Reactstrap's <Input> component. I want to programmatically deselect a selected object within it, so I am using state to control the value of the <select> and setting the state to be '' (an empty string) when I want to clear the state. However, this is having the effect of setting the first item in the select object to be selected, not deselecting it.

import React, { useState } from 'react';
import "./styles.css";
import {Input, Button} from 'reactstrap';

export default function App() {

  const [selectedOption, setSelectedOption] = useState<string>('');

  const onChangeSelection = (e: any) => {
    setSelectedOption(e.target.value);
  }

  const clearSelection = () => {
    setSelectedOption('');
  }

  return (
    <div className="App">
      <div>
        <Input type={"select"} size='2' value={selectedOption} onChange={onChangeSelection}>
          <option value={"option1"}>Option 1</option>
          <option value={"option2"}>Option 2</option>
        </Input>
      </div>
      <div>
        <Button onClick={clearSelection}>Clear selection</Button>
      </div>
    </div>
  );
}

There is an example of the problem

Edit jovial-wing-qw59p

How do I deselect any selected items?

Upvotes: 1

Views: 6254

Answers (1)

ThatAnnoyingDude
ThatAnnoyingDude

Reputation: 562

Add hidden option with value of empty string.

import React, { useState } from "react";
import "./styles.css";
import { Input, Button } from "reactstrap";

export default function App() {
  const [selectedOption, setSelectedOption] = useState<string>("");

  const onChangeSelection = (e: any) => {
    setSelectedOption(e.target.value);
  };

  const clearSelection = () => {
    setSelectedOption("hidden");
  };

  return (
    <div className="App">
      <div>
        <Input
          type={"select"}
          size="2"
          value={selectedOption}
          onChange={onChangeSelection}
        >
          <option value="" hidden></option>
          <option value={"option1"}>Option 1</option>
          <option value={"option2"}>Option 2</option>
        </Input>
      </div>
      <p>
        Clicking the clear button selects option 1, instead of deselecting any
        selected item.
      </p>
      <div>
        <Button onClick={clearSelection}>Clear selection</Button>
      </div>
    </div>
  );
}

Upvotes: 3

Related Questions