Kinda Code
Home/React/React + TypeScript: Handling Select onChange Event

React + TypeScript: Handling Select onChange Event

Last updated: March 03, 2023

A select element is a drop-down list with multiple options. In this article, we will examine an end-to-end example of handling the onChange event of a select element in a React web app that written with TypeScript.

The Example

App Preview

What we are going to build is a simple web app that has a select element in the center of the screen. When a user chooses one option from the drop-down list, the selected value will be displayed.

The Complete Code

1. Create a new project with the command below:

npx create-react-app kindacode_example --template typescript

2. Replace all of the default code in your src/App.tsx (or src/App.ts) with the following:

// App.tsx
// Kindacode.com
import React, { useState } from "react";

const App = () => {
  const [selectedOption, setSelectedOption] = useState<String>();

  // This function is triggered when the select changes
  const selectChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const value = event.target.value;
    setSelectedOption(value);
  };

  return (
    <div style={styles.container}>
      <select onChange={selectChange} style={styles.select}>
        <option selected disabled>
          Choose one
        </option>
        <option value="blue">Blue</option>
        <option value="red">Red</option>
        <option value="green">Green</option>
        <option value="yellow">Yellow</option>
        <option value="kindacode.com">Kindacode.com</option>
      </select>
      {selectedOption && <h2 style={styles.result}>{selectedOption}</h2>}
    </div>
  );
};

export default App;

// Just some styles
const styles: { [name: string]: React.CSSProperties } = {
  container: {
    marginTop: 50,
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
  },
  select: {
    padding: 5,
    width: 200,
  },
  result: {
    marginTop: 30,
  },
};

3. Run the project and go to http://localhost:3000 see the result:

npm start

Conclusion

You’ve learned how to handle the onChange event of a select element in React and TypeScript. If you would like to explore more new and interesting stuff about modern frontend development, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Related Articles